Content area
Full Text
Spring MVC is one of the most popular Java frameworks for building enterprise Java applications, and it lends itself very well to testing. By design, Spring MVC promotes the separation of concerns and encourages coding against interfaces. These qualities, along with Spring's implementation of dependency injection, make Spring applications very testable.
This tutorial is the second half of my introduction to unit testing with JUnit 5. I'll show you how to integrate JUnit 5 with Spring, then introduce you to three tools that you can use to test Spring MVC controllers, services, and repositories.
download
Get the code
Download the source code for example applications used in this tutorial. Created by Steven Haines for JavaWorld.
Integrating JUnit 5 with Spring 5
For this tutorial, we are using Maven and Spring Boot, so the first thing that we need to do is add the JUnit 5 dependency to our Maven POM file:
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.6.0</version>
<scope>test</scope>
</dependency>
Just like we did in Part 1, we'll use Mockito for this example. So, we're going to need to add the JUnit 5 Mockito library:
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>3.2.4</version>
<scope>test</scope>
</dependency>
@ExtendWith and the SpringExtension class
JUnit 5 defines an extension interface, through which classes can integrate with JUnit tests at various stages of the execution lifecycle. We can enable extensions by adding the @ExtendWith annotation to our test classes and specifying the extension class to load. The extension can then implement various callback interfaces, which will be invoked throughout the test lifecycle: before all tests run, before each test runs, after each test runs, and after all of the tests have run.
Spring defines a SpringExtension class that subscribes to JUnit 5 lifecycle notifications to create and maintain a "test context." Recall that Spring's application context contains all of the Spring beans in an application and that it performs dependency injection to wire together an application and its dependencies. Spring uses the JUnit 5 extension model to maintain the test's application context, which makes writing unit tests with Spring straightforward.
After we've added the JUnit 5 library to our Maven POM file, we can use the SpringExtension.class to extend our JUnit 5 test classes:
@ExtendWith(SpringExtension.class)
class MyTests {
// ...
}
The example, in this case,...