Search code examples
javajunitmockingclassloader

What error am I making with the ClassLoader getResources?


I have written the following code to test a method within my code. To create the s3Event, I have a json file but when I use the class loader I am always returned a null exception. It could be possible I have the absolute path incorrect? I have attached an image to show the file pathway layout in case this is the mistake.

@Test
@DisplayName("Testing the handleRequest")
void testTheHandleRequest() throws URISyntaxException, IOException {
    ClassLoader classLoader = getClass().getClassLoader();
    File file = new File(Objects.requireNonNull(classLoader.getResource("s3Event.json")).toURI());

    S3Event s3Event = new ObjectMapper().readValue(file, S3Event.class);
    Context context = null;
    LambdaHandler lambdaHandler = new LambdaHandler();

    assertEquals ("Finished handleRequest()", lambdaHandler.handleRequest(s3Event, null));
}

enter image description here


Solution

  • The only problem I could find is in the project structure. Maven supports the default ClassLoader resource behaviour for the default structure src/test/resources, whereas in your case the folder name is src/test/java/testResources, which requires additional configurations to be made either in POM or in program.

    My project folder structure is given below,

    enter image description here

    @Test
    @DisplayName("Testing on the classloader")
    public void testOnClassLoader() throws URISyntaxException {
        ClassLoader cl = getClass().getClassLoader();
    
        File file = new File(Objects.requireNonNull(cl.getResource("sample.json").toURI()));
    
        if(file != null) {
            System.out.println("File found "+ file.getAbsolutePath());
            assertEquals(true, true);
        }       
    
    }
    

    Output:

    -------------------------------------------------------
     T E S T S
    -------------------------------------------------------
    Running JsonLoaderTest
    File found ~\resource-access\target\test-classes\sample.json
    Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.139 sec
    
    Results :
    
    Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
    
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESS
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time:  7.007 s
    [INFO] Finished at: 2020-05-05T12:51:02+05:30
    [INFO] ------------------------------------------------------------------------
    

    Hope this helps.