Back to Repositories

Validating REST Controller Endpoints in spring-boot-examples

This test suite validates the HelloWorld controller functionality in a Spring Boot web application. It demonstrates proper setup and execution of controller tests using MockMvc, ensuring HTTP endpoints respond correctly with appropriate status codes.

Test Coverage Overview

The test coverage focuses on validating the basic functionality of the HelloWorld controller endpoint.

  • Tests the /hello endpoint GET request
  • Verifies successful HTTP 200 response
  • Validates 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 employs standalone setup with mock servlet context, allowing isolated controller testing without dependencies.

  • Uses SpringJUnit4ClassRunner for test execution
  • Implements MockMvc request builders
  • Employs fluent assertion API

Technical Details

  • JUnit 4 testing framework
  • Spring Test Context framework
  • MockMvc for HTTP request simulation
  • WebAppConfiguration for web context setup
  • MockServletContext for container simulation

Best Practices Demonstrated

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

  • Proper test initialization in @Before method
  • Clean separation of concerns
  • Isolated controller testing
  • Clear test method naming
  • Effective use of mock objects

ityouknow/spring-boot-examples

spring-boot-package/spring-boot-package-war/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.http.MediaType;
import org.springframework.mock.web.MockServletContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
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(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
public class HelloWorldControlerTests {

    private MockMvc mvc;

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

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

}