簡體   English   中英

SpringJUnit4ClassRunner在JUnit測試用例結束時不關閉Application Context

[英]SpringJUnit4ClassRunner does not close the Application Context at the end of JUnit test case

我在我的JUnit 4測試中使用SpringJUnit4ClassRunner,如下所示:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/test-context.xml"})
public class MyTest {
    @Autowired
    private ConfigurableApplicationContext context;
    @Test
    public void test1() {
    . . .
    }
    @Test
    public void test2() {
    . . .
    }
    . . .
}

但是,在此測試用例結束時,應用程序上下文未關閉。 我希望在測試用例結束時關閉應用程序上下文(不是在測試用例中的每個單獨測試結束時)。

到目前為止,我可以想出這個解決方法:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/test-context.xml"})
public class MyTest {
    @Autowired
    private ConfigurableApplicationContext context;
    private static ConfigurableApplicationContext lastContext;
    @After
    public void onTearDown() {
        lastContext = context;
    }
    @AfterClass
    public static void onClassTearDown() {
        lastContext.close();
    }
    @Test
    public void test1() {
    . . .
    }
    @Test
    public void test2() {
    . . .
    }
    . . .
}

有更好的解決方案嗎?

您可以在類級別添加@DirtiesContext(classMode=ClassMode.AFTER_CLASS) ,並且一旦方法中的所有測試完成,上下文將關閉。 您將獲得與當前代碼相同的功能。

你是如何運行測試的?

默認情況下,Spring不會在測試用例關閉時關閉上下文。 相反,它安裝JVM退出時運行的關閉掛鈎。 引入這種模糊的機制以允許測試上下文緩存 ,這是一件好事。

根據我的經驗,當從我的IDE和maven-surefire-plugin運行JUnit測試時,這可以正常工作。 你的解決方案有點黑客,當然不應該需要。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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