Java @SpringJUnit4ClassRunner中的AfterClass(如何在teardown中使用bean)

Java @SpringJUnit4ClassRunner中的AfterClass(如何在teardown中使用bean),java,spring,junit,Java,Spring,Junit,我想在spring单元测试(SpringJUnit4ClassRunner)中使用分解方法中的bean。 但是这个方法(用@AfterClass注释)应该是静态的。解决办法是什么 例如: @RunWith(SpringJUnit4ClassRunner.class) //.. bla bla other annotations public class Test{ @Autowired private SomeClass some; @AfterClass public void tearD

我想在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
}

}

也许您想使用@After而不是@AfterClass。它不是静态的。

也许您想使用@After而不是@AfterClass。它不是静态的。

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

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

也许我不想要@After,因为我不想在每个测试类上都进行重环境预处理。也许我不想要@After,因为我不想在每个测试类上都进行重环境预处理。这就是我喜欢TestNG的原因。这就是我喜欢TestNG的原因。