[英]SpringJUnit4ClassRunner does not close the Application Context at the end of JUnit test case
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? 有更好的解决方案吗?
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. 您可以在类级别添加
@DirtiesContext(classMode=ClassMode.AFTER_CLASS)
,并且一旦方法中的所有测试完成,上下文将关闭。 You will get the same functionality as your current code. 您将获得与当前代码相同的功能。
How are you running your tests? 你是如何运行测试的?
Spring is not closing the context by default on test case close. 默认情况下,Spring不会在测试用例关闭时关闭上下文。 Instead it install shutdown hook that is run when JVM exits.
相反,它安装JVM退出时运行的关闭挂钩。 This obscure mechanism was introduces to allow test context caching , which is a good thing.
引入这种模糊的机制以允许测试上下文缓存 ,这是一件好事。
From my experience this works correctly when JUnit tests are run both from my IDE and from maven-surefire-plugin
. 根据我的经验,当从我的IDE和
maven-surefire-plugin
运行JUnit测试时,这可以正常工作。 Your solution is a bit of a hack and certainly should not be needed. 你的解决方案有点黑客,当然不应该需要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.