如何为junit编写通用tearDown方法?

问题描述 投票:0回答:3

在我的项目(spring boot应用程序)中,我有大约200多个测试用例。最近,我们为我的启动类(@SpringBootApplication)中的缓存管理器(ehcache)实现了一个工厂bean。

我的问题是,一旦带有一个工厂用例的启动类被一个测试用例执行,所有随后的测试用例都将由于错误而失败...

“同一虚拟机中已存在另一个名为'appCacheManager'的CacheManager。“

为了解决这个问题,我为这样的身体添加了拆解方法……

public void tearDown() {
    MyCustomCacheManager customCacheManager = (MyCustomCacheManager) context.getBean("yourCustomCacheManagerBean");

    try {
        net.sf.ehcache.Cache cache = customCacheManager.getCache();
        net.sf.ehcache.CacheManager cacheManager = cache.getCacheManager();
        cacheManager.removeCache("nameOfYourCache");
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }

    context.destroy();
    context = null;
} 

我的问题是,我在所有现有的测试用例中都添加了这种拆解方法。

我们可以实现一些东西,以便在每个测试用例之后自动调用拆卸方法,我不必在每个JUNIT类中添加拆卸...

可能是在现有测试用例中带有一些注释的常规拆卸...

请咨询.....

java spring spring-boot junit ehcache
3个回答
0
投票

我正在考虑两种执行该方法的方法:

  1. [创建一个基类,每个单元测试都需要扩展该基类并在那里实现tearDown()方法。
  2. 使用AOP(面向方面​​的编程)以便在测试包中的每个方法之后执行tearDown()方法功能。

0
投票

它看起来好像是美国的JUnit 4,但是如果使用的是5,则可以write an extension允许您使用它注释测试类以注入行为。


0
投票

Spring正在使用TestExecutionListener实现此行为,您也可以。

只需创建具有以下内容的src/main/resources/META-INF/spring.factories文件:

org.springframework.test.context.TestExecutionListener=\
com.yourpackage.CacheTestExecutionListener

...并实现侦听器:

public class CacheTestExecutionListener implements TestExecutionListener {
    @Override
    public void afterTestMethod(TestContext testContext) throws Exception {
        // testContext.getApplicationContext().getBean(...)
    }
}

就应该这样-无需在现有测试中进行任何更改。

© www.soinside.com 2019 - 2024. All rights reserved.