Mocking Java InputStream

前端 未结 10 1673
既然无缘
既然无缘 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: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.

提交回复
热议问题