Spring Boot Testing - Integration tests for the Controller

Integration tests for the Controller

See

  1. https://github.com/explorer436/programming-playground/tree/main/java-playground/testing-examples
  2. https://github.com/explorer436/programming-playground/tree/main/java-playground/request-logging

Start the application. And then send an HTTP request and assert the response.

Start the application and listen for a connection (as it would do in production) and then send an HTTP request and assert the response. webEnvironment=RANDOM_PORT starts the server with a random port (useful to avoid conflicts in test environments). The port is injected with @LocalServerPort. Spring Boot automatically provides a TestRestTemplate for you. All you have to do is add @Autowired to it.

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.test.web.server.LocalServerPort;

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class HttpRequestTest {

   @LocalServerPort
   private int port;

   @Autowired
   private TestRestTemplate restTemplate;

   @Test
   public void greetingShouldReturnDefaultMessage() throws Exception {
           assertThat(this.restTemplate.getForObject("http://localhost:" + port + "/",
                           String.class)).contains("Hello, World");
   }
}

Reference

https://spring.io/guides/gs/testing-web

Tags

  1. Spring Boot Testing - MockMvc
  2. Spring Boot Testing - WebMvcTest