Search code examples
javatestingjmockit

Why is my second method's mock affecting the first method?


The class I've written has two methods, the second method containing a forced exception mock. When I run the tests separately they both pass but when they're run together the forced exception is called in the first method. I've tried tearDown but this method isn't available.

public class LambdaHandlerTest {

    @Test
    @DisplayName("Testing the handleRequest")
    void testTheHandleRequest() throws URISyntaxException, IOException {
        new MockUp<ProviderEvents>(){

            @Mock
            public File fetchFile(String bucket, String jobName, Context context) throws IOException{
                File file = new File ("src/test/resources/testEmailFile.txt");

                return file;
            }
        };

        new MockUp<AbstractAmazonSimpleEmailService>(){

            @Mock
            SendEmailResult sendEmail(SendEmailRequest var1){

                return null;
            }
        };

        LambdaHandler lambdaHandler = new LambdaHandler();

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

    @Test
    @DisplayName("Test catch block of handleRequest")
    void testCatchBlockHandleRequest() throws IOException, URISyntaxException {
        LambdaHandler lambdaHandler = new LambdaHandler();
        S3Event s3Event = generateS3Event();

        new MockUp<ServiceEvents>() {
            @Mock
            public Boolean extractJson(S3Event event, Context context) throws Exception {
                throw new Exception("Forced Exception");
            }
        };

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

    public S3Event generateS3Event() 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);

        return s3Event;
    }
}

Any help would be appreciated.


Solution

  • I'm not sure why it was happening but in the end I used @order to make sure the test with the mock that was throwing the forced exception was run last. Did the trick.