简体   繁体   English

为什么我的第二种方法的模拟会影响第一种方法?

[英]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.我写的 class 有两种方法,第二种方法包含强制异常模拟。 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.我试过 tearDown 但这种方法不可用。

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.任何帮助,将不胜感激。

INstead of having two method can you method the secod method to first one and check if both assert statement are excuted您可以将第二个方法用于第一个方法并检查两个断言语句是否都执行,而不是使用两种方法

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.我不确定为什么会发生这种情况,但最后我使用@order 确保使用抛出强制异常的模拟的测试最后运行。 Did the trick.成功了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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