简体   繁体   中英

@AfterClass in SpringJUnit4ClassRunner (how to use beans in teardown)

I want to use beans in tear-down method in spring unit test (SpringJUnit4ClassRunner). But this method (that is annotated with @AfterClass) should be static. 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. 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.

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

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM