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.
I hope you enjoy this little tip!