6

我试图了解如何测试用户的输入(请注意,我不是在尝试进行模拟测试,而是对实际用户输入的测试)

目前,正如您在我的程序中看到的那样,我已经对我的测试用例的值进行了硬编码,并且它通过了所有测试,但是我怎样才能获得用户的输入并对其进行测试。

有没有办法可以在我的构造函数中调用 System. 并在我在测试类中创建 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())));

}
}

谢谢你,我很感激任何帮助。

4

3 回答 3

7

使用System.setIn(new InputSteam());然后写入传入到 System.in 的输入流

请参阅:JUnit:如何模拟 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.
于 2013-04-17T17:50:47.757 回答
1

如果在 unix 上

java MyProgram < sampleinput.txt

于 2013-04-17T17:56:39.720 回答
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())));

}
于 2013-04-17T17:49:25.603 回答