<< Goodbye 2010 & Goodbye Innovations | Home | Integration of SocialEngine with external user administration >>

mockito, spring & AbstractJUnit4SpringContextTests

cleanup resources between unit test executions

I know some people consider it bad practise. But nethertheless I still believe that there is sometimes no alternative to tests that include startup of spring application contexts and initialization of in memory database. Actually I quite like those tests because if I don't include my database layer and my spring application contexts in my test I always have a bad felling about the quality of my software.

One problem with the setup described above is that sometimes resources are not cleaned up correctly between different @Test methods in a JUnit test case and sometimes even not cleanup between executions of different test classes in eclipse or in the maven surefire testrunner. Here is I how I deal with that:

Cleanup of h2

I'm using h2 within unit tests as a replacement for my production database like Oracle, SQL Server or MySQL. That most of the time works like a charm but sometimes the database is not correctly closed or deleted after a test case execution. Now I finally found a solution. H2 offers the nice DROP ALL OBJECTS DELETE FILES; command that drops all tables, views, users, etc. It will even delete the database files if the db was not created in in memory only mode.

Cleanup of Spring Resources

I'm using a simple Factory bean to create Mockito mocks for some of my services within the spring application context. Those mocks needs to be reset between test case execution. I could use the Mockito.reset() functionality but that is considered bad practise and quite error prone as I would need to provide a list of all my mocks to the method. Instead I'm now just shutting down my spring application context after the execution of each test method. The tests take a little bit longer this time but at least I can be sure that all resources are properly cleaned up. See the code snippet below for an example for an abstract Base Testclass that includes the functionality described above.



Re: mockito, spring & AbstractJUnit4SpringContextTests

I don't think anyone considers it bad pratice to do tests involving databases or spring contexts. It's just a question of terminology. Such a Test can NEVER be a unit test (therefore your abstract class is badly named) as it is not testing a single unit of code. It is therefore always an integration test. Nothing bad about doing integration tests using JUnit though.

Add a comment Send a TrackBack