Mocking Java InputStream

JavaMocking

Java Problem Overview


Please provide pointers to help me mock that java InputStream object. This is the line of code that I would wish to Mock:

InputStreamReader inputData = new InputStreamReader(System.in);
bufferdReader = new BufferedReader(inputData);
bufferdReader.readLine(); 

Java Solutions


Solution 1 - Java

You could use commons-io to create some stub input streams:

InputStream stubInputStream = 
     IOUtils.toInputStream("some test data for my input stream", "UTF-8");

Solution 2 - Java

You could just use a ByteArrayInputStream and fill it with your test data.

@Brad's example from the comments:

InputStream anyInputStream = new ByteArrayInputStream("test data".getBytes());

Solution 3 - Java

BufferedReader bufferedReader = org.mockito.Mockito.mock(BufferedReader.class);
when(bufferedReader.readLine())
  .thenReturn("first line")
  .thenReturn("second line");

org.junit.Assert.when(new Client(bufferedReader).parseLine())
  .thenEquals(IsEqual.equalTo("first line"));

Solution 4 - Java

I disagree with the selected answer for this question. Mocking frameworks like Mockito are nice and all, however when standard java api is available you might consider using that instead.

i.e.

BufferedReader reader = new BufferedReader(new StringReader("some string"));

Why use a Mock object in your test classes when you could use a real one with all its state and behaviour?

To see more about how this works, you could look up the 'decorator' design pattern.

Solution 5 - Java

@Test
    public void testReadFile() {
    TestClass ClassName = Mockito.mock(TestClass.class);
     InputStream in = Mockito.mock(InputStream.class);
     InputStreamReader inr =Mockito.mock(InputStreamReader.class);
     BufferedReader bufferedReader =Mockito.mock(BufferedReader.class);
       try {
         PowerMockito.whenNew(InputStreamReader.class).withArguments(in).thenReturn(inr);
         PowerMockito.whenNew(BufferedReader.class).withArguments(inr).thenReturn(bufferedReader);
         String line1 = "example line";
         PowerMockito.when(bufferedReader.readLine()).thenReturn(line1).thenReturn(null);
         method return type = Whitebox.invokeMethod(ClassName, "MethodName", arguement);
         assertEquals("result is::","expected", actual);
     } catch (Exception e) {
         e.printStackTrace();
     }
 }

Solution 6 - Java

Change your object so it is easier to test, something like this:

public MyObject {
    private InputStream inputStream;

    public void setInputStream(InputStream inputStream) {this.inputStream = inputStream;}

    public void whatever() {
        InputStreamReader inputData = new InputStreamReader(inputStream);
        bufferdReader = new BufferedReader(inputData);
        bufferdReader.readLine(); 
    }
}

then when you use your object initialize its inputStream first:

MyObject myObject = new MyObject();
myObject.setInputStream(System.in);

Now you have an object where you can test it using any implementation of InputStream you want (ByteArrayInputStream is a good one to try).

Solution 7 - Java

String testString = "test\nstring";
InputStream stream = new ByteArrayInputStream(testString.getBytes(StandardCharsets.UTF_8));

BufferedReader reader = new BufferedReader(new InputStreamReader(stream));

Assert.assertEquals("test", reader.readLine());
Assert.assertEquals("string", reader.readLine());

Solution 8 - Java

The best solution i found is use

final InputStream inputStream1 = IOUtils.toInputStream("yourdata");

and then wrap the inpustream in bufferedReader best way to write test around input Stream

Solution 9 - Java

Assuming you are using Maven you can put a resource into "src/test/resources/" folder let's say "src/test/resources/wonderful-mock-data.xml". Then in you jUnit your can do:

	String resourceInputFile = "/database-insert-test.xml";
	URL url = this.getClass().getResource(resourceInputFile);
	Assert.assertNotNull("Can't find resource " + resourceInputFile, url);

	InputStream inputStream = url.openStream();

	// Now you can just use the inputStream for method calls requiring this param
	(...)

In this example the url varialble will be null if the given resource can't be found inside current classpath. This approach allows you to put multiple scenarios inside different resourceInputFile(s)... Also remember that all kind of resources under "src/test/resources/" (not just xml files, any kind like txt, html, jpeg, etc.) are normaly available as classpath resources from all jUnit tests.

Solution 10 - Java

when(imageService.saveOrUpdate(Matchers.<Image>anyObject())).thenReturn(image);

Reference http://www.javased.com/?api=org.mockito.Matchers

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRejiView Question on Stackoverflow
Solution 1 - JavaEricView Answer on Stackoverflow
Solution 2 - JavapapView Answer on Stackoverflow
Solution 3 - JavaBoris PavlovićView Answer on Stackoverflow
Solution 4 - JavaJohn DeverallView Answer on Stackoverflow
Solution 5 - JavaPentayyaView Answer on Stackoverflow
Solution 6 - Javaпутин некультурная свиньяView Answer on Stackoverflow
Solution 7 - JavaeyveerView Answer on Stackoverflow
Solution 8 - JavaPriteshView Answer on Stackoverflow
Solution 9 - JavaA. MassonView Answer on Stackoverflow
Solution 10 - Java取一个好的名字View Answer on Stackoverflow