如何在Junit控制台中接受来自用户的输入 [英] how to accept input from user in Junit console

查看:130
本文介绍了如何在Junit控制台中接受来自用户的输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为下面给出的函数编写Junit测试用例:

I am trying to write Junit test case for the function given below:

class A{
  int i;
  void set()
  {
    Scanner in=new Scanner(System.in);
    i=in.nextInt();
  }
}

现在我的问题是我创建一个Junit测试用例对于它,它不会从用户输入:

Now my problem is when i create a Junit test case for it, it does not except input from user:

 public void testSet() throws FileNotFoundException {
    System.out.println("set");
    A instance = new A();
    int i=1;
    instance.set(i);
    // TODO review the generated test code and remove the default call to fail.
    //fail("The test case is a prototype.");
}

请注意我应该怎样接受用户的输入。

Please suggets what should i do to accept input from user.

推荐答案

你可以使用 System.setIn() 模拟用户输入:

You can use System.setIn() to mock user input:

String inputData = "user input data";
System.setIn(new java.io.ByteArrayInputStream(inputData.getBytes()));

现在如果你打电话给 set()它将从您的字符串而不是标准输入中读取数据。

Now if you call your set() method it will read the data from your string rather than from standard input.

这篇关于如何在Junit控制台中接受来自用户的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆