What does this do: @RunWith(SpringJUnit4ClassRunne

2019-04-19 12:47发布

问题:

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?

回答1:

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.



回答2:

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 = FooHarness.class)
class FooHarnessTest {

    @Autowired
    FooHarness fooHarness 

Now when you use fooHarness in a unit test it will have have a Spring context setup for it. So any beans that fooHarness injects will also be setup.

If the beans that fooHarness injects 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 the fooHarness or any of its injected beans reads Spring config then you need to add an initializers list to the @ContextConfiguration annotation, that contains the ConfigFileApplicationContextInitializer class:

@ContextConfiguration(classes = FooHarness.class, initializers = ConfigFileApplicationContextInitializer.class)


标签: spring junit