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

250
February 28, 2018, at 5:46 PM

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");
Answer 1

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.

Answer 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.

Rent Charter Buses Company
READ ALSO
refreshing cahche assignment thread safety

refreshing cahche assignment thread safety

I have a cache refresh logic as shown above and like to make sure that it's thread safe and right way to do it

164
Mobile Vision API to scan entire line

Mobile Vision API to scan entire line

I found Mobile Vision API to extract blocks, lines and wordsIt reading the line with contiguous words

203
Elasticsearch, spring, react search for users

Elasticsearch, spring, react search for users

I am using using react, spring and elastic search and I would like to make a function that displays all users in the database (ES) with a given nameI need to make an axios call to list users from the database and be able to input different parameters...

278