I have a unit test that is run with SpringJUnit4ClassRunner as follows:
@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. Static members cannot be injected.
How can i do that through a listener or any other means?
Thx.
You can use @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"
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:aConfig.xml")
@TestExecutionListeners(listeners = {ShutdownExecutionListener.class},
mergeMode = MergeMode.MERGE_WITH_DEFAULTS)
public class TestService
{
@Resource
EmbeddedMysqlDatabase mysqlDB;
...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.