Skip to content

spring-guides/gs-testing-web

This guide walks you through the process of creating a Spring application and then testing it with JUnit.

What You Will Build

You will build a simple Spring application and test it with JUnit. You probably already know how to write and run unit tests of the individual classes in your application, so, for this guide, we will concentrate on using Spring Test and Spring Boot features to test the interactions between Spring and your code. You will start with a simple test that the application context loads successfully and continue on to test only the web layer by using Spring’s MockMvc.

Starting with Spring Initializr

You can use this pre-initialized project and click Generate to download a ZIP file. This project is configured to fit the examples in this tutorial.

To manually initialize the project:

  1. Navigate to https://start.spring.io. This service pulls in all the dependencies you need for an application and does most of the setup for you.

  2. Choose either Gradle or Maven and the language you want to use.

  3. Click Dependencies and select Spring Web and HTTP Client.

  4. Click Generate.

  5. Download the resulting ZIP file, which is an archive of a web application that is configured with your choices.

Note
If your IDE has the Spring Initializr integration, you can complete this process from your IDE.
Note
You can also fork the project from GitHub and open it in your IDE or other editor.

Create a Simple Application

Create a new controller for your Spring application. The following listing shows how to do so:

Java
link:complete/src/main/java/com/example/testingweb/HomeController.java[role=include]
Kotlin
link:complete-kotlin/src/main/kotlin/com/example/testingweb/HomeController.kt[role=include]

Run the Application

The Spring Initializr creates an application class (a class with a main() method) for you. For this guide, you need not modify this class. The following listing shows the application class that the Spring Initializr created:

Java
link:complete/src/main/java/com/example/testingweb/TestingWebApplication.java[role=include]
Kotlin
link:complete-kotlin/src/main/kotlin/com/example/testingweb/TestingWebApplication.kt[role=include]

You can run this application class from your IDE directly, or from the command line using Gradle (./gradlew :bootRun) or Maven (./mvwn spring-boot:run).

Now that the application is running, you can test it. You can load the home page at http://localhost:8080. However, to give yourself more confidence that the application works when you make changes, you want to automate the testing.

Test the Application

Spring Boot assumes you plan to test your application, so it adds the necessary dependencies to your build file (build.gradle or pom.xml).

The first thing you can do is write a simple sanity check test that will fail if the application context cannot start. The following listing shows how to do so:

Java
link:initial/src/test/java/com/example/testingweb/TestingWebApplicationTests.java[role=include]
Kotlin
link:initial-kotlin/src/test/kotlin/com/example/testingweb/TestingWebApplicationTests.kt[role=include]

The @SpringBootTest annotation tells Spring Boot to look for a main configuration class (one with @SpringBootApplication, for instance) and use that to start a Spring application context. You can run this test in your IDE or on the command line (by running ./mvnw test or ./gradlew check), and it should pass. To convince yourself that the context is creating your controller, you could add an assertion, as the following example shows:

Java
link:complete/src/test/java/com/example/testingweb/SmokeTest.java[role=include]
Kotlin
link:complete-kotlin/src/test/kotlin/com/example/testingweb/SmokeTest.kt[role=include]

Spring interprets the @Autowired annotation, and the controller is injected before the test methods are run. We use AssertJ (which provides assertThat() and other methods) to express the test assertions.

It is nice to have a sanity check, but you should also write some tests that assert the behavior of your application. To do that, you could start the application and listen for a connection (as it would do in production) and then send an HTTP request and assert the response. The following listing shows how to do so:

Java
link:complete/src/test/java/com/example/testingweb/HttpRequestTest.java[role=include]
Kotlin
link:complete-kotlin/src/test/kotlin/com/example/testingweb/HttpRequestTest.kt[role=include]

Note the use of webEnvironment=RANDOM_PORT to start the server with a random port (useful to avoid conflicts in test environments) and the injection of the port with @LocalServerPort. Also, note that Spring Boot has automatically provided a RestTestClient for you because we expressed the need for it with @AutoConfigureRestTestClient. All you have to do after that is to add @Autowired to the field.

Another useful approach is to not start the server at all but to test only the layer below that, where Spring handles the incoming HTTP request and hands it off to your controller. That way, almost all of the full stack is used, and your code will be called in exactly the same way as if it were processing a real HTTP request but without the cost of starting the server. To do that, we can reuse our previous test using RestTestClient, but this time leaving @SpringBootTest with its default, which is to start a mock server environment. The following listing shows how to do so:

Java
link:complete/src/test/java/com/example/testingweb/TestingWebApplicationTest.java[role=include]
Kotlin
link:complete-kotlin/src/test/kotlin/com/example/testingweb/TestingWebApplicationTest.kt[role=include]

In this test, the full Spring application context is started but without the server. We can narrow the tests to only the web layer by using @WebMvcTest, as the following listing shows:

Java
link:complete/src/test/java/com/example/testingweb/WebLayerTest.java[role=include]
Kotlin
link:complete-kotlin/src/test/kotlin/com/example/testingweb/WebLayerTest.kt[role=include]

The test assertion is the same as in the previous case. However, in this test, Spring Boot instantiates only the web layer rather than the whole context. In an application with multiple controllers, you can even ask for only one to be instantiated by using, for example, @WebMvcTest(HomeController.class).

So far, our HomeController is simple and has no dependencies. We could make it more realistic by introducing an extra component to store the greeting (perhaps in a new controller). The following example shows how to do so:

Java
link:complete/src/main/java/com/example/testingweb/GreetingController.java[role=include]
Kotlin
link:complete-kotlin/src/main/kotlin/com/example/testingweb/GreetingController.kt[role=include]

Then create a greeting service, as the following listing shows:

Java
link:complete/src/main/java/com/example/testingweb/GreetingService.java[role=include]
Kotlin
link:complete-kotlin/src/main/kotlin/com/example/testingweb/GreetingService.kt[role=include]

Spring automatically injects the service dependency into the controller (because of the constructor signature). The following listing shows how to test this controller with @WebMvcTest:

Java
link:complete/src/test/java/com/example/testingweb/WebMockTest.java[role=include]
Kotlin
link:complete-kotlin/src/test/kotlin/com/example/testingweb/WebMockTest.kt[role=include]

We use @MockitoBean to create and inject a mock for the GreetingService (if you do not do so, the application context cannot start), and we set its expectations using Mockito.

Summary

Congratulations! You have developed a Spring application and tested it with JUnit and Spring MockMvc and have used Spring Boot to isolate the web layer and load a special application context.

About

Testing the Web Layer :: Learn how to test Spring Boot applications and MVC controllers.

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Packages

No packages published

Contributors 18