【问题标题】:Why is my second method's mock affecting the first method?为什么我的第二种方法的模拟会影响第一种方法?
【发布时间】:2020-05-06 08:10:51
【问题描述】:

我编写的类有两个方法,第二个方法包含一个强制异常模拟。当我分别运行测试时,它们都通过了,但是当它们一起运行时,在第一种方法中调用了强制异常。我试过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;
    }
}

任何帮助将不胜感激。

【问题讨论】:

    标签: java testing jmockit


    【解决方案1】:

    您可以将第二个方法用于第一个方法并检查两个断言语句是否都执行

    ,而不是有两个方法

    【讨论】:

      【解决方案2】:

      我不确定为什么会发生这种情况,但最后我使用@order 来确保使用引发强制异常的模拟的测试最后运行。成功了。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-17
        • 2022-01-20
        相关资源
        最近更新 更多