java SpringJUnit4ClassRunner 不会在 JUnit 测试用例结束时关闭 Application Context

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7498202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 20:14:39  来源:igfitidea点击:

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

javaspringjunit

提问by rustyx

I'm using SpringJUnit4ClassRunner in my JUnit 4 tests like this:

我在 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() {
    . . .
    }
    . . .
}

However, at the end of this test case the application context is not closed. I would like to have the application context closed at the end of the test case (NOT at the end of each individual unit-test in the test case).

但是,在此测试用例结束时,应用程序上下文并未关闭。我希望在测试用例结束时关闭应用程序上下文(而不是在测试用例中每个单独的单元测试结束时)。

So far I could come up with this work-around:

到目前为止,我可以想出这个解决方法:

@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() {
    . . .
    }
    . . .
}

Is there a better solution?

有更好的解决方案吗?

回答by gkamal

You can add the @DirtiesContext(classMode=ClassMode.AFTER_CLASS)at the class level and the context will get closed once all the tests in the methods are done. You will get the same functionality as your current code.

您可以@DirtiesContext(classMode=ClassMode.AFTER_CLASS)在类级别添加 ,一旦方法中的所有测试完成,上下文就会关闭。您将获得与当前代码相同的功能。

回答by Tomasz Nurkiewicz

How are you running your tests?

你如何运行你的测试?

Spring is not closing the context by default on test case close. Instead it install shutdown hook that is run when JVM exits. This obscure mechanism was introduces to allow test context caching, which is a good thing.

默认情况下,Spring 不会在测试用例关闭时关闭上下文。相反,它安装了在 JVM 退出时运行的关闭钩子。这种晦涩的机制被引入以允许测试上下文缓存,这是一件好事。

From my experience this works correctly when JUnit tests are run both from my IDE and from maven-surefire-plugin. Your solution is a bit of a hack and certainly should not be needed.

根据我的经验,当 JUnit 测试同时从我的 IDE 和maven-surefire-plugin. 您的解决方案有点麻烦,当然不需要。