Back to Repositories

Testing REST Endpoint Responses with MockMvc in spring-boot-examples

This test suite demonstrates Spring Boot REST endpoint testing using MockMvc for the HelloController. It validates basic HTTP request handling and response content verification in a standalone test environment.

Test Coverage Overview

The test suite focuses on validating the ‘/hello’ endpoint response handling.

Key areas covered include:
  • HTTP GET request processing
  • Response status code verification
  • Response content validation
  • 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 HelloController for focused unit testing, leveraging SpringRunner for test execution context management.

Technical implementation features:
  • MockMvcBuilders standalone configuration
  • Request builder pattern usage
  • Fluent assertion chaining

Technical Details

Testing infrastructure includes:
  • JUnit 4 test framework
  • Spring Boot Test context
  • MockMvc for request simulation
  • Hamcrest matchers for assertions
  • SpringRunner test executor

Best Practices Demonstrated

The test implementation showcases several testing best practices in Spring Boot applications.

Notable practices include:
  • Proper test setup isolation using @Before
  • Clear test method naming
  • Focused single-responsibility test methods
  • Explicit media type specification
  • Clean assertion structure

ityouknow/spring-boot-examples

2.x/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")));
    }

}