Back to Repositories

Testing Spring Boot REST Controller Endpoints in spring-boot-examples

This test suite demonstrates Spring Boot controller testing using MockMvc for REST endpoint validation. It focuses on testing a simple Hello World endpoint with proper HTTP response validation and content verification.

Test Coverage Overview

The test coverage focuses on validating the basic functionality of a REST endpoint in the HelloController. Key aspects tested include:

  • HTTP GET request handling
  • 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 implementation leverages standalone setup for controller testing, demonstrating a focused unit testing strategy that isolates the controller behavior.

The test uses Spring Runner and SpringBootTest annotations for proper Spring context integration.

Technical Details

Testing tools and configuration include:

  • JUnit 4 as the testing framework
  • SpringRunner for test execution
  • MockMvc for REST endpoint simulation
  • MockMvcBuilders for test environment setup
  • Hamcrest matchers for response validation

Best Practices Demonstrated

The test suite exemplifies several testing best practices:

  • Proper test isolation using @Before setup
  • Clear test method naming
  • Specific assertion checking for both status and content
  • Clean separation of test setup and execution
  • Use of fluent assertion style for better readability

ityouknow/spring-boot-examples

1.x/spring-boot-actuator/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")));
    }

}