简体   繁体   中英

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?

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 (eg src/test/resources if you're using Maven), and put whatever test content in it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM