ICE09 . playing with java, scala, groovy and spring .

Playing with Spring

  • Archives

  • Advertisements

Quick Tip: Testing Spring

Posted by ice09 on July 12, 2008

Download Eclipse project

You can read detailed and good written documentation about unit testing with Spring here.
But as always, when combining Spring with Maven using Eclipse, some things have to be considered.

  • Create a “no archetype” Maven project in Eclipse (compare the other posts).
  • Create the test case first (following TDD) with Eclipse. This can be a JUnit 3 or 4 test case.
  • Afterwards, within Eclipse the class generation can easily be done using the Quick Fix funtionality (Strg + 1).

The test case must extends Spring’s AbstractDependencyInjectionSpringContextTests, making it much easier to use Spring in unit tests. It is best combined with the call to setPopulateProtectedVariables(true) in the constructor. Using this feature, Spring can inject Beans into protected fields, avoiding the need for setters in test cases.
By defining getConfigLocations(), special Spring configfiles for unit tests can be chosen. However, using Maven, we are always seperating test and main resources (compare project structure).

Test case:

package test.sample;

import org.springframework.test.AbstractDependencyInjectionSpringContextTests;

public class SpringTest extends AbstractDependencyInjectionSpringContextTests {

	protected BeanUnderTest testbean;

	public SpringTest() {

	public void testBeanUnderTest() {
		assertEquals(1, testbean.return1());

	protected String[] getConfigLocations() {
		return new String[]{"applicationContext-test.xml"};

Class under test (BeanUnderTest):

package test.sample;

public class BeanUnderTest {

	public int return1() {
		return 1;


applicationContext-test.xml (currently this is the only config):

<?xml version="1.0" encoding="UTF-8"?>

	<bean id="testbean" class="test.sample.BeanUnderTest"/>


And the Maven POM. It is important to include the Compiler 5 switches if JUnit 4 is used:

<project xmlns="" xmlns:xsi=""
	<description />

That’s it, Maven, JUnit and Spring can be combined very smoothly and Spring again shows with the AbstractDependencyInjectionSpringContextTests how it provides the useful little glue between these components.


One Response to “Quick Tip: Testing Spring”

  1. […] – bookmarked by 6 members originally found by crapshaw on 2008-08-31 Quick Tip: Testing Spring – bookmarked by 4 members […]

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: