Unit tests vs integration tests with Spring

I can’t speak to being a best practice, but here’s what I’ve done in the past.

Unit tests:

  • Create unit tests for non-trivial beans (ie, most of your Spring related beans)
  • Use Mocks for injected services where practical (ie, most if not all the time).
  • Use a standard naming convention for these tests in the project test directory. Using Test or TestCase as a prefix or suffix to the classname seems to be widely practiced.

Integration Tests:

  • Create an AbstractIntegrationTestCase that sets up a Spring WebApplicationContext for use in intetgration test clases.
  • Use a naming convention for integration tests in the test directory. I’ve used IntTest or IntegrationTest as a prefix or suffix for these tests.

Set up three Ant test targets:

  1. test-all (or whatever you want to name it): Run Unit and Integration Tests
  2. test: Run Unit tests (just because test seems to be the most common usage for unit testing
  3. test-integration: run the integration tests.

As noted, you can use the naming conventions that make sense for your project.

As to separating unit from integration tests into a separate directory, I don’t think it matters as long as the developers and their tools can find and execute them easily.

As an example, the last Java project I worked on with Spring used exactly what is described above, with integration tests and unit tests living in the same test directory. Grails projects, on the other hand, explicitly separate unit and integration test directories under a general test directory.

Leave a Comment