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!