1

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");
Nalin Adhikari
  • 586
  • 2
  • 6
  • 15

2 Answers2

1

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.

ernest_k
  • 44,416
  • 5
  • 53
  • 99
-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.

yılmaz
  • 1,818
  • 13
  • 15