[英]How to mock System.in in Java (except using inside Junit Test Case)?
I have used TextFromStandardInputStream with JUnit Test Case, which works fine. 我已经将TextFromStandardInputStream与JUnit测试用例一起使用,效果很好。 But now I want to mock StandardInputStream outside Test Cases for my requirements.
但是现在我想在测试用例之外模拟StandardInputStream以满足我的需求。 I have used the same TextFromStandardInputStream outside the Test Case but it didn't work at all.
我在测试用例之外使用了相同的TextFromStandardInputStream,但是根本没有用。 So, is there any way to do the work done?
那么,有什么方法可以完成工作吗?
Sample of StandardInputStream with Test Case that I have used
我使用过的带有测试用例的StandardInputStream的示例
@Rule
public final TextFromStandardInputStream systemInMock = emptyStandardInputStream();
Inside Test Case : 内部测试案例:
systemInMock.provideLines("1","2");
You could set system in to your mock by using System.setIn()
, assuming you've stubbed your input stream: 您可以使用
System.setIn()
将系统设置为模拟对象,并假设已对输入流进行了存根处理:
System.setIn(systemInMock);
This works with a normal input stream: 这适用于普通输入流:
System.setIn(new ByteArrayInputStream("yes".getBytes()));
System.out.println(System.in.read());// outputs 121
Likewise, you can reset it if you stored it in a variable before setting System.in
to the value of the mock. 同样,如果在将
System.in
设置为模拟值之前将其存储在变量中,则可以重置它。
You can use Aspect Oriented Programming
to intercept to System.in
and do mocking instead of calling real System.in
. 您可以使用
Aspect Oriented Programming
来拦截到System.in
并进行模拟,而不是调用实际的System.in
。 AspectJ
or Spring AOP
might be a starting point. AspectJ
或Spring AOP
可能是一个起点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.