Back to Repositories

Testing Spring Boot Controller Endpoints in spring-boot-examples

This test suite validates the functionality of a Spring Boot Hello World controller using JUnit and MockMvc testing framework. It demonstrates proper setup and execution of HTTP endpoint testing in a Spring Boot application with actuator capabilities.

Test Coverage Overview

The test suite focuses on validating the basic HTTP GET endpoint ‘/hello’ functionality.

Key areas covered include:
  • HTTP response status verification
  • Request handling for JSON media type
  • Basic endpoint availability testing

Implementation Analysis

The testing approach utilizes Spring’s MockMvc framework for simulating HTTP requests without requiring a full server deployment. The implementation leverages standalone setup pattern with MockMvcBuilders, enabling isolated controller testing.

Technical patterns include:
  • MockMvc request building
  • Response status assertion
  • Request result logging

Technical Details

Testing stack includes:
  • JUnit 4 test runner
  • SpringRunner for Spring context integration
  • MockMvc for HTTP request simulation
  • Spring Boot Test framework
  • MediaType handling for JSON responses

Best Practices Demonstrated

The test suite exemplifies several testing best practices in Spring Boot applications.

Notable practices include:
  • Proper test initialization using @Before
  • Clean separation of setup and test logic
  • Use of standalone setup for controller isolation
  • Clear test method naming conventions

ityouknow/spring-boot-examples

1.x/spring-boot-actuator/src/test/java/com/neo/controller/HelloWorldControlerTests.java

            
package com.neo.controller;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

@RunWith(SpringRunner.class)
@SpringBootTest
public class HelloWorldControlerTests {

    private MockMvc mvc;

    @Before
    public void setUp() throws Exception {
        mvc = MockMvcBuilders.standaloneSetup(new HelloController()).build();
    }

    @Test
    public void getHello() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn();
    }

}