简体   繁体   中英

How to mock System.in in Java (except using inside Junit Test Case)?

I have used TextFromStandardInputStream with JUnit Test Case, which works fine. But now I want to mock StandardInputStream outside Test Cases for my requirements. I have used the same TextFromStandardInputStream outside the Test Case but it didn't work at all. So, is there any way to do the work done?

Sample of StandardInputStream with Test Case that I have used

@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(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.

You can use Aspect Oriented Programming to intercept to System.in and do mocking instead of calling real System.in . AspectJ or Spring AOP might be a starting point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM