[英]@AfterClass in SpringJUnit4ClassRunner (how to use beans in teardown)
I want to use beans in tear-down method in spring unit test (SpringJUnit4ClassRunner). 我想在弹簧单元测试(SpringJUnit4ClassRunner)的拆卸方法中使用bean。 But this method (that is annotated with @AfterClass) should be static.
但是此方法(用@AfterClass注释)应该是静态的。 What can be the solution?
有什么解决方案?
example: 例:
@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
}
}
Perhaps you want to use @After instead of @AfterClass. 也许您想使用@After而不是@AfterClass。 It isn't static.
它不是静态的。
JUnit uses a new instance for each test method, so in @AfterClass
execution the Test instance don't exists and you can't access to any member. JUnit为每个测试方法使用一个新实例,因此在
@AfterClass
执行中,该Test实例不存在,并且您无法访问任何成员。
If you really need it, you could add a static member to the test class with the application context and set it manually using an TestExecutionListener
如果确实需要,可以将静态成员添加到带有应用程序上下文的测试类中,并使用
TestExecutionListener
手动设置它
for example: 例如:
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.