簡體   English   中英

SpringJUnit4ClassRunner中的@AfterClass(如何在拆卸中使用bean)

[英]@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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM