JUnit & Spring, integration testing

JUnit & Spring, JUnit integration testing example.

Unit tests are great, but they cover only part of your code. Another interesting category of tests is integration testing. Using integration tests you can test collaboration of objects, methods for accessing database etc.

If you use Spring, it's very easy. In Spring you have a Service or Repository like this service class. Now I want to test these methods.

First I must add Spring runner using: @RunWith(SpringJUnit4ClassRunner.class). Next I must specify where is XML configuration file on disc using @ContextConfiguration. I also strongly suggest to add @Transactional annotation to your test suite. Thanks to this annotation after each test will be automatically called rollback. You can also call rollback on your own using @Rollback. This test suite is now like a Spring bean, you can use annotation @Autowired to inject Spring beans.