首页 > 解决方案 > 如何使用 JUnit 测试运行时异常场景

问题描述

我有以下需要测试的课程。我可以测试课程,但在这种情况下如何测试异常场景,因为我无法模拟ObjectMapper课程。

package xyz.util;

import ...

public class JsonConverter {

    private static ObjectMapper mapper;

    static {
        mapper = new ObjectMapper();
        mapper.writerWithDefaultPrettyPrinter();
    }

    private JsonConverter() {}

    public static String toJson(Object object) {

        try {
            return mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            throw new AppplicationRuntimeException("Exception while converting object to JSON", e);
        }
    }


    public static <T> T toObject(String jsonString, Class<T> clazz) {
        try {
            return mapper.readValue(jsonString, clazz);
        } catch (IOException e) {
            throw new AppRuntimeException("Exception while converting JSON to Object", e);
        }
    }
}

标签: junit

解决方案


如果可以 - 消除静态呼叫。例如,ObjectMapper通过构造函数显式注入被测类:

public class JsonConverter {

    private final ObjectMapper mapper;

    public JsonConverter(ObjectMapper mapper) {
       this.mapper = mapper;
    }

    // rest of the code
}

但是,如果无法更改代码,您可以使用Powermock模拟带有异常的静态调用。

此外,要结合 JUnit 断言不同的异常场景,您可以使用AssertJ fluent API。


推荐阅读