Back to Repositories

Testing REST Controller Endpoints in spring-boot-examples

This test suite demonstrates Spring Boot REST API testing using MockMvc for the HelloWorldController. It validates endpoint responses and HTTP status codes through standalone setup, showcasing essential Spring Boot testing patterns.

Test Coverage Overview

The test coverage focuses on validating the /hello endpoint’s response behavior and HTTP status codes. Key functionality includes:
  • GET request handling verification
  • Response status validation
  • Request acceptance of JSON media type
  • Endpoint availability testing

Implementation Analysis

The testing approach utilizes MockMvc for simulating HTTP requests without a full server deployment. It implements standalone controller testing using SpringRunner and SpringBootTest annotations, enabling isolated controller testing without loading the full application context.

Technical Details

Testing tools and configuration include:
  • JUnit 4 testing framework
  • MockMvc for request simulation
  • SpringRunner for test execution
  • MockMvcBuilders for standalone setup
  • MockMvcResultMatchers for response validation
  • MockMvcResultHandlers for output logging

Best Practices Demonstrated

The test suite exemplifies several testing best practices:
  • Proper test initialization using @Before
  • Isolated controller testing through standalone setup
  • Clear test method naming
  • Explicit media type specification
  • Structured request building and response validation

ityouknow/spring-boot-examples

2.x/spring-boot-package/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();
    }

}