Back to Repositories

Testing REST Endpoint Response Handling in spring-boot-examples

This test suite demonstrates Spring Boot REST endpoint testing using MockMvc and JUnit. It validates the HelloController’s response handling and HTTP status codes through standalone configuration.

Test Coverage Overview

The test suite provides focused coverage of the basic REST endpoint functionality in the HelloController.

Key areas tested include:
  • HTTP GET request handling
  • Response status code validation
  • Response content verification
  • JSON media type acceptance

Implementation Analysis

The testing approach utilizes Spring’s MockMvc framework for simulating HTTP requests without a full server deployment. The standalone setup pattern isolates the controller under test, enabling fast and focused unit testing of the REST endpoint behavior.

Notable implementation features:
  • MockMvcBuilders standalone configuration
  • Fluent assertion chaining
  • Spring Runner integration

Technical Details

Testing stack components:
  • JUnit 4 test framework
  • Spring Boot Test context
  • MockMvc for request simulation
  • Hamcrest matchers for assertions
  • SpringRunner for test execution

Best Practices Demonstrated

The test class exemplifies several testing best practices for Spring Boot applications.

Notable practices include:
  • Clean test setup using @Before annotation
  • Isolated controller testing through standalone configuration
  • Explicit media type specification
  • Clear assertion chains
  • Focused test scope

ityouknow/spring-boot-examples

spring-boot-package/spring-boot-package/src/test/java/com/neo/controller/HelloTests.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.setup.MockMvcBuilders;

import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

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

	
    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(status().isOk())
                .andExpect(content().string(equalTo("Hello World")));
    }

}