我使用JUnit测试我的具有控制台输入的程序,并使用ByteArrays来模拟控制台输入和输出。但由于某种原因,当我在第一次测试结束时使用System.setIn(IS)时,它实际上并没有改变System.in。同样在第二次测试中,当我尝试将新的ByteArray作为System.in时,它没有发生,我的第二次测试无法通过......那么为什么会这样呢?
编辑:我的Utility类使用Scanner从System.in读取。 :
public static String readText() {
while (true) {
String unos = sc.nextLine();
if (!unos.isEmpty()) {
return unos;
}
System.out.println("Niste ništa uneli, pokušajte ponovo: ");
}
}
public static String read() {
String unos = sc.nextLine();
return unos;
}
这些是我的测试:
private final InputStream IS = System.in;
private final PrintStream PS = System.out;
@Test
public void testRead() {
ByteArrayInputStream in = new ByteArrayInputStream("\nNeki tekst\nasdasdasd".getBytes());
System.setIn(in);
assertEquals("", Utility.read());
assertEquals("Neki tekst", Utility.read());
System.setIn(IS);
}
@Test
public void testReadText() {
ByteArrayInputStream in = new ByteArrayInputStream("\nNeki tekst2\n".getBytes());
System.setIn(in);
ByteArrayOutputStream out = new ByteArrayOutputStream();
System.setOut(new PrintStream(out));
assertEquals("Neki tekst2", Utility.readText());
assertEquals("Niste ništa uneli, pokušajte ponovo: " + System.getProperty("line.separator"), out.toString());
System.setIn(IS);
System.setOut(PS);
}