Spring Boot测试中使用REST Assured(转)

 

原文:https://rieckpil.de/testing-spring-boot-applications-with-rest-assured/

REST Assured is a Java DSL (Domain Specific Langauge) that aims to simplify testing REST APIs. It follows a BDD (Behavior Driven Development) approach and is influenced by testing APIs with dynamic languages like Groovy. We can use REST Assured to test the REST API of any Java project as it is framework independent. However, REST Assured comes with a great Spring integration for testing our @RestController endpoints that we're about to explore with this article.

Spring Boot and REST Assured Project Setup

For our demo application we use Java 11, Spring Boot 2.4.0, and the following dependencies:

As Spring Boot manages the dependency version of REST Assured and all its modules, we can define the spring-mock-mvc without an explicit version. We can override the managed version consistently with the rest-assured.version property.

If we mix up our dependency versions for REST Assured and try to outsmart Spring Boot, we might see several exceptions during test runtime:

As REST Assured has quite some transitive dependencies (Groovy related dependencies, Apache HttpClient, Hamcrest, and Tagsoup), we should favor the manged version from our Spring Boot release.

As I've seen several integration issues for REST Assured and Java 11 projects, consider the following tips:

  • IntelliJ IDEA can help to identify duplicated dependency includes for a Maven project. We can open a visual dependency graph with the following steps: right-click inside our pom.xml -> Maven -> Show Dependencies. A red arrow indicates a violation for dependency convergence. The Maven Enforcer plugin can even detect this as part of your build.
  • REST Assured also provides a rest-assured-all dependency, that can help to solve split package problems.
  • When using Spring Boot together with REST Assured, you might also stumble over exceptions for Groovy related parts of this testing library. Explicitly overriding Spring Boot's default Groovy version with groovy.version inside the pom.xml seems to help here.

The Spring MVC RestController Under Test

Our sample application is a book store that exposes the following REST API endpoints to manage its inventory:

The actual implementation of the BookService doesn't matter for this demonstration and we can assume it stores our book entities somewhere (e.g. database or in-memory).

For a more realistic example, we'll secure the HTTP POST endpoint and only allow authenticated users that have the ADMIN role to access it:

 
Mockito & JUnit Cheat Sheet

JUnit 5 & Mockito Cheat Sheet

Answering 24 questions for the two most essential Java testing libraries.

 

REST Assured Powered MockMvc Test

There are multiple ways to configure REST Assured for a Spring MVC test case. We can manually pass a list of controller objects, provide a MockMvcBuilder , pass a WebApplicationContext or a MockMvc instance.

As we can inject an already initialized MockMvc bean to our test when using Spring Boot's test slice annotation @WebMvcTest, we'll use it for our REST Assured configuration.

All upcoming requests for this test class will target this MockMvc instance unless we override it explicitly.

With this setup in place, we can write our first test that ensures unauthenticated clients can request our book store's inventory:

Due to REST Assured's fluent API, one should easily grasp the test setup above. REST Assured also follows a BDD style and  .given().when().then() gives each request a standardized schema.

For writing expectations for our HTTP response body/status/header, we then use Matchers from Hamcrest.

The test above doesn't use static imports because there is a small pitfall. When importing the .given() method from REST Assured, we have to make sure it's not the traditional non-Spring variant:

Furthermore, there is a potential second pitfall when using a static import and Mockito in the same test.

For tests where we don't need a .given() step (e.g., we don't pass any query parameter/path variable/header), we can omit it and start our request specification with .when() :

As soon as we add a static import for REST Assured's .when() we would clash with Mockito's .when() unless we are more explicit and use Mockito.when(). This is something to keep in mind.

Testing a Protected Endpoint

Most tutorials end here as they showed how to test only one Hello World API endpoint. But that's not what we aim for. Let's take it to the next step and write a test for our protected HTTP POST endpoint.

REST Assured already comes with great support for several authentication mechanisms. Besides that, we can integrate the SecurityMockMvcRequestPostProcessors from the spring-security-test dependency that we might be already familiar with from other MockMvc tests.

As part of the .given() step, we define the HTTP request body, set the content type, and associate a user. The Spring Security Test RequestPostProcessor functionality gives us full control over the user setup (username, password, roles, authorities) for this test.

We can also use the @WithMockUser annotation for our tests:

 

Further Tips For REST Assured with Spring Boot

For Spring WebFlux controller endpoints that use the WebTestClient for tests, REST Assured provides a spring-web-test-client module. There are also extensions and support for both Scala and Kotlin available.

While REST Assured is designed to verify and test REST APIs, we can also test @Controller endpoints with the spring-mock-mvc module.

Let's assume one of our controller endpoints returns a Thymeleaf view and populates its Model. As we can add any ResultMatcher to our .then() verification part, we can write the following expectation:

However, REST Assured won't provide any additional syntactic sugar or helper methods to verify @Controller endpoints and we just use Spring's MockMvcResultMatchers.

We can also use REST Assured when writing integration tests for our Spring Boot application. Let's verify that we can create a book and a subsequent query for the book returns it:

Keep in mind that we don't use MockMvc and access our Spring Boot application on a local port for such an integration test. That's why we have to replace RestAssuredMockMvc.given() with RestAssured.given().

Summary of using REST Assured with Spring Boot

Due to the feature-rich and convenient API of MockMvc and Spring Boot's excellent test support, I wouldn't consider REST Assured a must-have. The spring-mock-mvc module is basically a wrapper on top of MockMvc that brings REST Assured's fluent API to it. However, REST Assured still offers great features on top:

If your team is already familiar with REST Assured from testing REST APIs of other projects (e.g. non-Spring Boot), it's surely a good fit for your Spring Boot application. Once resolve potential incompatibility issues and are aware of the pitfalls, REST Assured can be a great add-on for your testing toolbox.

All source code examples for this REST Assured with Spring Boot demo are available on GitHub.

Have fun using REST Assured with Spring Boot,

Philip

posted @ 2021-05-12 03:05  奋斗终生  Views(269)  Comments(0Edit  收藏  举报