我正在进行一些集成测试,在集成测试之前将数据加载到远程测试数据库中。但是,它包含大量数据,因此我宁愿在所有集成测试之前只执行一次。
我已经使用 @BeforeClass/@AfterClass 使用 @RunWith(Suite.class) 和 JUnitCore.runClasses() 将我的所有测试类作为套件运行。然而,我一直困惑于如何让 Spring Autowiring 安装和拆卸所需的资源。示例:
public class AbstractTest {
@Autowired
private SessionFactory sf;
@BeforeClass
public static void setup() {
sf.getCurrentSession().createQuery("make tables");
}
}
但是 sf 始终为 null,因为 @BeforeClass 需要从静态上下文运行。 我还尝试使用@ClassRule,如下所示:How to share JUnit BeforeClass logic among multiple test classes 但没有任何变化;
如何获得一组测试类的 @BeforeClass/@AfterClass 功能并在 @BeforeClass/@AfterClass 方法中拥有 Autowired 资源?让它与 @Parameterized 一起运行会更好。
最佳答案
SpringJUnit4ClassRunner 在 autowired 之前调用 BeforeClass 。 Context 已构造,但尚未注入(inject),需在调用 BeforeClass 方法后注入(inject)。
from RunBeforeTestClassCallbacks :
public void evaluate() throws Throwable {
for (FrameworkMethod before : befores) { -- call for BeforeClass methods
before.invokeExplosively(target);
}
next.evaluate(); -- call DependencyInjectionTestExecutionListener
--where context is injected
}
你可以尝试这个(而不是@BeforeClass,使用InitializingBean中的afterPropertiesSet - 它在BeforeClass调用但在所有测试统计执行之前执行)
public abstract class AbstractTest implements InitializingBean{
@Autowired
private SessionFactory sf;
//@BeforeClass
@Override
public void afterPropertiesSet() throws Exception {
sf.getCurrentSession().createQuery("make tables");
}
或
public abstract class AbstractTest {
private static SessionFactory sf;
@Autowired
public void setSessionFactory (SessionFactory sf){
AbstractTest.sf = sf;
setup();
}
//@BeforeClass
public static void setup() {
sf.getCurrentSession().createQuery("make tables");
}
}
无论如何,这都可以解决,因为测试类的 BeforeClass 在 spring context 之前被单元化。
<小时/>变体 2,已更新
@TestExecutionListeners(listeners = {AbstractTest.class, DependencyInjectionTestExecutionListener.class})
public class AbstractTest extends AbstractTestExecutionListener {
public static SessionFactory sf;
@BeforeClass
public static void setup() {
sf.getCurrentSession().createQuery("make tables");
}
@Override
public void beforeTestClass(TestContext testContext) throws Exception {
sf = testContext.getApplicationContext().getBean(SessionFactory.class);
super.beforeTestClass(testContext);
}
}
关于java - 想要使用共享的 @BeforeClass/@AfterClass 和 Spring App Context 运行许多 jUnit 测试类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44794560/