如何在我的异常类中模拟一个类?

时间:2019-10-10 05:29:44

标签: spring-boot unit-testing mockito

我必须在MyException类中访问ApplicationContext

public class MyException extends Exception {
    public MyException(Map<String, Map<String,String>> errorObj) throws IOException {
            ApplicationContext applicationContext = ApplicationContextProvider.getApplicationContext();
            Environment env = applicationContext.getEnvironment();
            ...
    }
}

此服务将其抛出。

 @Service
 public class MyServiceImpl implements MyService {

    @Override
    public Response myFunction() {

          throw new MyException(errorObj);
       ...
    }
 }

编辑为ApplicationContextProvider

public class ApplicationContextProvider implements ApplicationContextAware {

    private static ApplicationContext context;

    public static ApplicationContext getApplicationContext(){
        return context;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }
}

当我运行unittest时,我在ApplicationContext上收到了NullPointerException。我想模拟ApplicationContext怎么做?

我仅在单元测试中发现了此错误,但是当我使用spring-boot运行时,它运行正常

1 个答案:

答案 0 :(得分:0)

您可以在测试类中使用SpringBootTest批注,以创建一个包含所有测试所需对象的应用程序。