【发布时间】:2011-11-21 19:53:58
【问题描述】:
我在 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() {
. . .
}
. . .
}
有没有更好的解决方案?
【问题讨论】: