Mocking Java InputStream

前端 未结 10 1638
既然无缘
既然无缘 2020-11-29 04:40

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 I         


        
相关标签:
10条回答
  • 2020-11-29 05:01

    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());
    
    0 讨论(0)
  • 2020-11-29 05:04

    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

    0 讨论(0)
  • 2020-11-29 05:04

    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.

    0 讨论(0)
  • 2020-11-29 05:08
    when(imageService.saveOrUpdate(Matchers.<Image>anyObject())).thenReturn(image);
    

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

    0 讨论(0)
提交回复
热议问题