我想在spring单元测试(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
}
}发布于 2013-02-26 03:17:25
也许你想使用@After而不是@AfterClass。它不是静态的。
发布于 2013-02-26 03:57:33
JUnit为每个测试方法使用一个新的实例,因此在@AfterClass执行中,测试实例不存在,并且您不能访问任何成员。
如果确实需要,可以使用应用程序上下文将静态成员添加到测试类中,并使用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);
}
}https://stackoverflow.com/questions/15074602
复制相似问题