What does this do: @RunWith(SpringJUnit4ClassRunner.class)

What does this annotation do?
When would I want to use it?
When would I not want to use it?

@RunWith(SpringJUnit4ClassRunner.class)

I can find more usages of this when I Google and do not find a 101 explanation as to what this annotation is supposed to communicate to me or when/why I would use it?


The annotation is used to configure a unit test that required Spring's dependency injection.

From Spring Reference - 10. Unit Testing:

10.1 Creating a Unit Test Class

In order for the unit test to run a batch job, the framework must load the job's ApplicationContext. Two annotations are used to trigger this:

@RunWith(SpringJUnit4ClassRunner.class): Indicates that the class should use Spring's JUnit facilities.

@ContextConfiguration(locations = {...}): Indicates which XML files contain the ApplicationContext.


If you are using annotations rather than XML files, then any class that you are unit testing that requires Spring dependency injection needs to be put into the @ContextConfiguration annotation. For example:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = FooManager.class)
class FooManagerTest {
    
    @Autowired
    FooManager fooManager;

Now when you use fooManager in a unit test it will have have a Spring context setup for it.

If fooManager autowires in any beans then those bean's classes also need to be in the @ContextConfiguration annotation. So if fooManager autowires in a FooReporter bean:

@ContextConfiguration(classes = {FooManager.class, FooReporter.class})

If the beans that fooManager autowires in contain state, then you will likely want to reset the state of those beans for each test. In that case you can add the @DirtiesContext annotation to your test class:

@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)

If fooManager or any of its autowired beans reads Spring config then you need to add an initializers list to the @ContextConfiguration annotation, that contains the ConfigFileApplicationContextInitializer class:

@ContextConfiguration(classes = {FooManager.class, FooReporter.class}, initializers = ConfigFileApplicationContextInitializer.class)