Java 模拟用户输入中的System.in的Junit测试
我试图创建一个Junit测试,在用户输入后测试输出。我目前正在尝试的是:Java 模拟用户输入中的System.in的Junit测试,java,junit5,Java,Junit5,我试图创建一个Junit测试,在用户输入后测试输出。我目前正在尝试的是: @Before public void setStreams() { System.setOut(new PrintStream(out)); System.setErr(new PrintStream(err)); } @After public void restoreInitialStreams() { System.setO
@Before
public void setStreams() {
System.setOut(new PrintStream(out));
System.setErr(new PrintStream(err));
}
@After
public void restoreInitialStreams() {
System.setOut(originalOut);
System.setErr(originalErr);
}
@Test
public void displayTest() {
Scanner sc = new Scanner(System.in);
ByteArrayInputStream in = new ByteArrayInputStream("X".getBytes());
System.setIn(in);
System.out.println(sc.next());
Assert.assertEquals("X", out.toString());
}
但是我遇到了一个问题,当我尝试运行测试时,它永远不会完成测试(加载动画)。我假设我试图模拟用户输入错误,但我不确定还有什么可以尝试。您的
扫描仪
是从真实的系统读取的。在
中,而不是从ByteArrayOutputStream中,因为您在更新系统之前创建了扫描仪。在
中,如果您创建扫描仪
稍后
@Test
public void displayTest() {
ByteArrayInputStream in = new ByteArrayInputStream("X".getBytes());
System.setIn(in);
Scanner sc = new Scanner(System.in);
System.out.println(sc.next());
Assert.assertEquals("X", out.toString());
}
如果您测试与<代码>系统交互的代码。在,<代码>系统。它们可以帮助您完成此类测试所需的设置代码,并避免常见错误。免责声明:我是这些库的作者