我想了解如何测试用户的输入(请注意我不是要进行模拟测试,而是测试实际用户的输入)
目前正如您在我的程序中看到的那样,我已经对我的测试用例进行了硬编码,并且它通过了所有测试,但我如何获得用户的输入并进行测试。
有没有办法在构造函数中调用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())));
}
}
谢谢你,我感谢任何帮助。
答案 0 :(得分:5)
使用System.setIn(new InputSteam());
然后写入传入System.in
请参阅:JUnit: How to simulate System.in testing?
单一输入
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 :(得分:0)
用户扫描程序类
public void testNumbers()
{
Scanner scan = new Scanner(System.in);
System.out.println("value1");
int value1 = scan.nextInt();
System.out.println("value2");
int value2 = scan.nextInt();
System.out.println("value3");
int value3 = scan.nextInt();
MyClass1 numbers= new MyClass1(value1, value2, value3);
assertThat(numbers.getValue1(),is(not(numbers.getValue2())));
}
答案 2 :(得分:0)
如果在unix上
java MyProgram < sampleinput.txt