Kirill_Batutin
Kirill_Batutin

Reputation: 11

How can I mock InputStream getResourceAsStream in java?

I have this code

public QueryConfigurationSupplier(String fileName) throws IOException {
    Scanner scanner;
    if (fileName.startsWith("/opt/ankey")) {
        Reader reader = new FileReader(fileName);
        scanner=new Scanner(reader);
    } else {
        InputStream inputStream=this.getClass().getClassLoader().getResourceAsStream(fileName);
        scanner=new Scanner(inputStream);
    }


@Test
public void testQueryConfiguration() throws IOException {
    InputStream in = mock(InputStream.class);
    ClassLoader classloader = mock(ClassLoader.class);
    final URLConnection mockConnection = Mockito.mock(URLConnection.class);
    when(mockConnection.getInputStream()).thenReturn(new ByteArrayInputStream(EMPTY_BYTE_ARRAY));
    String resource = "oracle/odb_conf.txt";
    when(classloader.getResourceAsStream(resource)).thenReturn(in);
    QueryConfigurationSupplier queryConfigurationSupplier=new QueryConfigurationSupplier("oracle/odb_conf.txt");
    
}

And when I execute it I get NPE from Scanner because inputStream is null. How do it right?

Upvotes: 0

Views: 1034

Answers (1)

M A
M A

Reputation: 72844

You're creating a mock InputStream and ClassLoader, but the code is still using this.getClass().getClassLoader() to load the file, which cannot be modified.

A much better way to implement the test is to create a test file under your test resources directory (e.g. src/test/resources if you're using Maven), and put whatever test content in it.

Upvotes: 0

Related Questions