在我的项目(spring boot应用程序)中,我有大约200多个测试用例。最近,我们为我的启动类(@SpringBootApplication)中的缓存管理器(ehcache)实现了一个工厂bean。
我的问题是,一旦带有一个工厂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类中添加拆解...
可能是现有测试用例中的一些带有某些注释的常规拆解...
请咨询.....
答案 0 :(得分:0)
我正在考虑两种实现方法:
答案 1 :(得分: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(...)
}
}
就应该如此-无需在现有测试中进行任何更改。
答案 2 :(得分:0)
它看起来确实像是Usain JUnit 4,但是如果您使用的是5,则可以write an extension来注释测试类以注入行为。