我已将 TextFromStandardInputStream 与 JUnit 测试用例一起使用,效果很好。但现在我想在测试用例之外模拟 StandardInputStream 以满足我的要求。我在测试用例之外使用了相同的 TextFromStandardInputStream 但它根本不起作用。那么,有什么办法可以完成已完成的工作吗?
Sample of StandardInputStream with Test Case that I have used
@Rule
public final TextFromStandardInputStream systemInMock = emptyStandardInputStream();
内部测试用例:
systemInMock.provideLines("1","2");
最佳答案
假设您已经对输入流进行了 stub 处理,您可以使用 System.setIn()
将系统设置到您的模拟中:
System.setIn(systemInMock);
这适用于普通输入流:
System.setIn(new ByteArrayInputStream("yes".getBytes()));
System.out.println(System.in.read());// outputs 121
同样,如果在将 System.in
设置为模拟值之前将其存储在变量中,则可以重置它。
关于java - 如何在 Java 中模拟 System.in(除了在 Junit 测试用例中使用)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49022345/