Skip to content

Test

Spring Boot Testing Guide

Spring Boot provides various tools and annotations to help developers effectively test their applications. Testing can be divided into unit testing, integration testing, and end-to-end testing. This document outlines some commonly used testing annotations and features.

@SpringBootTest

  • Purpose: Loads the entire Spring application context, suitable for integration testing.
  • Functionality: Starts a complete Spring Boot application context, including all Beans and configurations.
  • Example:

  @SpringBootTest
  public class MyServiceTest {

      @Autowired
      private MyService myService;

      @Test
      public void testService() {
          assertNotNull(myService);
      }
  }

@MockBean

•   Purpose: Creates mock objects in Spring Boot tests and injects them into the Spring container.
•   Functionality: Replaces Beans in the application context to simulate the behavior of dependencies.
•   Example:

    @SpringBootTest
    public class MyServiceTest {
        @MockBean
        private MyRepository myRepository;

        @Autowired
        private MyService myService;

        @Test
        public void testService() {
            when(myRepository.findById(1L)).thenReturn(Optional.of(new MyEntity()));
            assertNotNull(myService.getEntityById(1L));
        }
    }

@WebMvcTest

•   Purpose: Tests Spring MVC controllers, creating a minimal Spring context.
•   Functionality: Loads only the Web layer Beans, not the full application context.
•   Example:

    @WebMvcTest(MyController.class)
    public class MyControllerTest {

        @Autowired
        private MockMvc mockMvc;

        @Test
        public void testController() throws Exception {
            mockMvc.perform(get("/my-endpoint"))
                .andExpect(status().isOk())
                .andExpect(content().string("Hello, world!"));
        }
    }


@DataJpaTest

•   Purpose: Tests Spring Data JPA components, creating a context with only JPA-related Beans.
•   Functionality: Focuses on the data access layer, automatically configuring an embedded database.
•   Example:

        @DataJpaTest
        public class MyRepositoryTest {

            @Autowired
            private MyRepository myRepository;

            @Test
            public void testRepository() {
                MyEntity entity = new MyEntity();
                myRepository.save(entity);
                assertNotNull(myRepository.findById(entity.getId()));
            }
        }

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)

•   Purpose: Tests the entire Spring Boot application, including the Web layer, by starting an embedded web server with a random port.
•   Functionality: Suitable for integration tests that require real HTTP requests.
•   Example:

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

        @LocalServerPort
        private int port;

        @Test
        public void testHttpEndpoint() throws Exception {
            URL url = new URL("http://localhost:" + port + "/my-endpoint");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            assertEquals(200, connection.getResponseCode());
        }
    }


Common Testing Tools and Methods

MockMvc

•   Purpose: Used to test Spring MVC controllers by simulating HTTP requests and responses to verify controller behavior.
•   Example:

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void testController() throws Exception {
        mockMvc.perform(get("/endpoint"))
            .andExpect(status().isOk())
            .andExpect(content().string("Expected content"));
    }


TestRestTemplate

•   Purpose: Used to test RESTful APIs in Spring Boot applications, providing access to the embedded web server.
•   Example:

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    public void testRestApi() {
        ResponseEntity<String> response = restTemplate.getForEntity("/endpoint", String.class);
        assertEquals(HttpStatus.OK, response.getStatusCode());
        assertEquals("Expected content", response.getBody());
    }

@AutoConfigureMockMvc

•   Purpose: Configures and injects a MockMvc instance for Web layer testing.
•   Example:

    @AutoConfigureMockMvc
    @SpringBootTest
    public class MyControllerTest {

        @Autowired
        private MockMvc mockMvc;

        @Test
        public void testController() throws Exception {
            mockMvc.perform(get("/endpoint"))
                .andExpect(status().isOk())
                .andExpect(content().string("Expected content"));
        }
    }

---