[英]Add a junit listener to a SpringJUnit4ClassRunner
I have a unit test that is run with SpringJUnit4ClassRunner as follows: 我有一个使用SpringJUnit4ClassRunner运行的单元测试,如下所示:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:aConfig.xml")
public class TestService
{
@Resource
EmbeddedMysqlDatabase mysqlDB;
...
}
I have an embedded database that used in the unit tests that I would like to shutdown after all test have been run. 我有一个嵌入式数据库,用于单元测试,我想在运行所有测试后关闭。 I know embedding a database in a unit test is not usual/good practice but in this particular case this is super useful. 我知道在单元测试中嵌入数据库不是通常的/良好实践,但在这种特殊情况下,这是非常有用的。
@AfterClass is not an option because it has to be static and my database instance is injected by spring. @AfterClass不是一个选项,因为它必须是静态的,我的数据库实例是由spring注入的。 Static members cannot be injected. 静态成员不能注入。
How can i do that through a listener or any other means? 我怎么能通过听众或任何其他方式做到这一点?
Thx. 谢谢。
You can use @TestExecutionListeners. 您可以使用@TestExecutionListeners。 Something like this: 像这样的东西:
public class ShutdownExecutionListener extends AbstractTestExecutionListener {
@Override
public void beforeTestClass(TestContext testContext) throwsException {
}
@Override
public void afterTestClass(TestContext testContext) throws Exception{
EmbeddedMysqlDatabase mysqlDB=
(EmbeddedMysqlDatabase)testContext.getApplicationContext().getBean(mysqlDB);
mysqlDB.shutdown();
}
}
And in your test: 在你的测试中:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:aConfig.xml")
@TestExecutionListeners(listeners = ShutdownExecutionListener.class)
public class TestService
{
@Resource
EmbeddedMysqlDatabase mysqlDB;
...
}
Works great, but don't forget to set "mergeMode" 效果很好,但不要忘记设置“mergeMode”
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:aConfig.xml")
@TestExecutionListeners(listeners = {ShutdownExecutionListener.class},
mergeMode = MergeMode.MERGE_WITH_DEFAULTS)
public class TestService
{
@Resource
EmbeddedMysqlDatabase mysqlDB;
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.