Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a junit listener to a SpringJUnit4ClassRunner

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.

like image 869
isaac.hazan Avatar asked Oct 25 '25 18:10

isaac.hazan


2 Answers

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;

     ...
}
like image 163
Antonio Attadia Avatar answered Oct 27 '25 06:10

Antonio Attadia


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;
    ...
}
like image 29
user5891746 Avatar answered Oct 27 '25 08:10

user5891746