如何在java中对用户输入进行单元测试
我试图了解如何测试用户的输入(请注意我不是在尝试模拟测试,而是测试实际用户的输入)。目前正如您在我的程序中看到的那样,我已经对我的测试用例的值进行了硬编码,并且它正在通过所有测试但是我如何获得用户的输入并进行测试。
有没有办法在我的构造函数中调用System.in并在测试类中创建MyClass1实例时传递它?
请尽可能给我一些示例代码,以便我能更好地理解。
如果我有这样的接口:public interface IMyClass{
public int getvalue1();
public int getvalue2();
public int getvalue3();
}
然后接口实现:
public class MyClass1 implements MyClass{
private int _value1 = 0;
private int _value2 = 0;
private int _value3 = 0;
public MyClass1(int number1, int number2, int number3)
{
_value1 = number1;
_value2 = number2;
_value3 = number3;
}
public void setLength1(int value1)
{
_value1 = value1;
}
public void setLength2(int length2)
{
_value2 = value2;
}
public void setLength3(int length3)
{
_value3 = value3;
}
public int getValue1()
{
return _value1;
}
public int getValue2()
{
return _value2;
}
public int getValue3()
{
return _value3;
}
}最后是一个测试类:
public class ClasTest extends TestCase {
public void testNumbers()
{
MyClass1 numbers= new MyClass1(1,2,3);
assertThat(numbers.getValue1(),is(not(numbers.getValue2())));
}
}谢谢你,我感谢任何帮助。
解决方法:
请在文本框输入文字使用System.setIn(new InputSteam());然后写入传入System.in的输入流。
单输入
String data = "Users Input";
System.setIn(new ByteArrayInputStream(data.getBytes()));
Scanner scanner = new Scanner(System.in);
System.out.println(scanner.nextLine());结果
Users Input多输入
String data = "Users Input" +
"\nA second line of user input.";
System.setIn(new ByteArrayInputStream(data.getBytes()));
Scanner scanner = new Scanner(System.in);
System.out.println("Line 1: " + scanner.nextLine());
System.out.println("Line 2: " + scanner.nextLine());结果
Line 1: Users Input
Line 2: A second line of user input.
页:
[1]