New way to test your REST API with Spring
Spring Framework 6.2 was released, and now we have a new and better way to test our REST endpoints. Let’s see how we can do it.
AssertJ
AssertJ is a fluent test library to create assertions. It is easier to use and to read than JUnit 5. For example:
Using org.assertj.core.api.Assertions
@Test
void testCreateOrder() {
when(productService.getProductById(1L)).thenReturn(Optional.of(new Product(1L, "Keyboard", BigDecimal.valueOf(20.5))));
when(orderService.createOrder(1L, 1L)).thenReturn(new Order(1L, 2L, 1L));
OrderDto order = orderAggregateService.createOrder(1L, 1L);
assertThat(order.id()).isEqualTo(2L);
assertThat(order.quantity()).isEqualTo(1L);
assertThat(order.productId()).isEqualTo(1L);
}
If we compare it with JUnit5 we have this result:
Using org.junit.jupiter.api.Assertions
@Test
void testCreateOrder() {
when(productService.getProductById(1L)).thenReturn(Optional.of(new Product(1L, "Keyboard", BigDecimal.valueOf(20.5))));
when(orderService.createOrder(1L, 1L)).thenReturn(new Order(1L, 2L, 1L));
OrderDto order = orderAggregateService.createOrder(1L, 1L);
assertEquals(order.id(), 2L);
assertEquals(order.quantity(), 1L);
assertEquals(order.productId(), 1L);
}
You may think the difference is not too big because of this example. I wrote an article showing many advantages of using AssertJ, you can have a look here: Test Assertions in Java the best way
But the goal is not to talk about AssertJ, is to talk about Spring, so let’s see the news from Spring.
MockMvcTester
Spring introduces a MockMvc Tester that integrates with AssertJ, making our API tests clearer and easier to read than ever.
Someone asked if this was possible in 2015, and now this will be possible to do. This new feature was introduced in Spring 6.2, and Spring Boot 3.4.0.
We can use this new feature by creating the MockMvcTester for our class, for example:
private final MockMvcTester mockMvc = MockMvcTester.of(new ContentNegotiationController());
And then our test
@DisplayName("Should return content from v1")
@Test
void testGetValuesV1() {
org.assertj.core.api.Assertions.assertThat(mockMvc
.get()
.uri("/content-negotiation")
.accept("application/vnd.my.api.v1+json"))
.hasStatusOk()
.hasBodyTextEqualTo("Content Negotiation v1");
}
This is only one example of how we can use it and make your text more fluent and easy to read.
You can have a look at the code on my repo on GitHub: https://github.com/ThiagoBfim/spring-versioning-testing.
Conclusion
Spring is improving and introducing new and better ways to do old things, MockMvcTester is a good way to test your REST API using a fluent API. To keep up with the latest updates, subscribe for free!