Writing JUnit using the Spring context

In the previous sections, we looked at how to launch a Spring context from the main method. Now let's shift our attention to launching a Spring context from a unit test.

We can use SpringJUnit4ClassRunner.class as a runner to launch a Spring context:

    @RunWith(SpringJUnit4ClassRunner.class)

We would need to provide the location of the context configuration. We will use the XML configuration that we created earlier. Here's how you can declare this:

    @ContextConfiguration(locations = {      "/BusinessApplicationContext.xml" })

We can autowire a bean from the context into the test using the @Autowired annotation. BusinessService is autowired by the type:

    @Autowired     private BusinessService service;

As of now, ...

Get Mastering Spring 5.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.