[英]@AfterClass in SpringJUnit4ClassRunner (how to use beans in teardown)
我想在弹簧单元测试(SpringJUnit4ClassRunner)的拆卸方法中使用bean。 但是此方法(用@AfterClass注释)应该是静态的。 有什么解决方案?
例:
@RunWith(SpringJUnit4ClassRunner.class)
//.. bla bla other annotations
public class Test{
@Autowired
private SomeClass some;
@AfterClass
public void tearDown(){
//i want to use "some" bean here,
//but @AfterClass requires that the function will be static
some.doSomething();
}
@Test
public void test(){
//test something
}
}
也许您想使用@After而不是@AfterClass。 它不是静态的。
JUnit为每个测试方法使用一个新实例,因此在@AfterClass
执行中,该Test实例不存在,并且您无法访问任何成员。
如果确实需要,可以将静态成员添加到带有应用程序上下文的测试类中,并使用TestExecutionListener
手动设置它
例如:
public class ExposeContextTestExecutionListener extends AbstractTestExecutionListener {
@Override
public void afterTestClass(TestContext testContext) throws Exception {
Field field = testContext.getTestClass().getDeclaredField("applicationContext");
ReflectionUtils.makeAccessible(field);
field.set(null, testContext.getApplicationContext());
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners(listeners={ExposeContextTestExecutionListener.class})
@ContextConfiguration(locations="classpath:applicationContext.xml")
public class ExposeApplicationContextTest {
private static ApplicationContext applicationContext;
@AfterClass
public static void tearDown() {
Assert.assertNotNull(applicationContext);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.