Unit Test Spring Applications

Unit Test Spring Applications
Everyone is using the Spring Framework to build their Java applications these days, aren’t they? The Spring Application Context allows you to easily construct and set-up objects and then use them to create others – but are developers always using this to drive their unit tests?

It would appear not.  I constantly come across unit tests written that instantiate the class under test and then populate it manually or that programatically grab the class and manually set it up. Dont get me wrong, this still tests that the class does as you expect, but it doesn’t test the Spring wiring and it takes alot more effort…  Effort you have already expended!

Save yourself some time (and pain) by using the SpringJUnit4ClassRunner class.

How to use SpringJUnit4ClassRunner

Basically you just annotate your unit test class with @RunWith and @ContextConfiguration, giving them the JUnit Class Runner to use and the Appliation Context(s) to use respectively.

This instructs the JUnit test to use the given Application Context natively and allows you to just grab beans defined within – the @Autowired and @Qualifier combo make this really simple and concise.


package com.macbtech.blog.testing;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@ContextConfiguration(locations = {"classpath*:spring/application-context.xml"})
public class ServiceTest {

	@Autowired @Qualifier("primaryService")
    private TheService service;

    public void testService() throws Exception {
        final ServiceResult result = service.doSomething();

Leave a Reply

Your email address will not be published. Required fields are marked *