Running unit tests with the Spring Framework

Ever wondered how to create unit tests with the Spring Framework?  It’s actually quite simple using Spring’s TestContext Framework.  Here’s just a quick sample.  Of course the same information is available in the docs.  The first most important thing is the @RunWith annotation which is one of JUnit’s annotations.  Setting this annotation’s value to SpringJUnit4ClassRunner.class tells JUnit to use Spring’s TestContext Framework test runner, rather than JUnit’s built in test runner.  The second important thing is the @ContextConfiguration annotation which is a Spring annotation.  It’s responsible for telling Spring where to find your application context.  It could be given a single value or a String[] of values.  Spring’s TestContext Framework does come with some added annotations for writing your unit tests, but the normal JUnit annotations work just the same.  If all you’re looking to do is wire up some Spring managed beans, then this is the easiest way to do so.

import static org.junit.Assert.*;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:/META-INF/spring/applicationContext.xml")
public class TestPhoneTrace {

	@Autowired
	private PhoneLog phoneLog;

	@Test
	public void testPhoneLogIsReadable() {
		assertTrue("Phone log is not readable.", phoneLog.isReadable());
	}

	@Test
	public void testPhoneLogHasRecords() {
		assertTrue("Phone log does not have records.", phoneLog.hasRecords());
	}
}

I hope you enjoy this little tip!

About these ads

2 Comments on “Running unit tests with the Spring Framework

  1. What about a hibernate sessionFactory? This does not work if you try to autowire a session factory from an application context configured to use a LocalSessionFactoryBean

    • That’s a bit beyond the scope of this simple example. It was written over 3 years ago too. Today I typically use Spring Data JPA and @Bean configuration. Injecting or autowiring a repository is very straight forward in this case. No need to deal directly with the sessionFactory, unless your project has a specific requirement to do so.

      Thanks for your comment :)

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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

Follow

Get every new post delivered to your Inbox.

Join 82 other followers

%d bloggers like this: