Sample code to unit test a Spring Boot controller with MockMvc

This environment

Controller to be tested and Thymeleaf template

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class FooBarController {

  @GetMapping("/")
  public ModelAndView topPage(ModelAndView mav) {
    mav.setViewName("index");
    mav.addObject("userName", "Alice");
    return mav;
  }
}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>My App</title>
</head>
<body>
<p id="user-name" th:text="${userName}"></p>
</body>
</html>

Class to test the controller

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpHeaders;
import org.springframework.test.web.servlet.MockMvc;

import static org.hamcrest.Matchers.containsString;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;

@SpringBootTest
@AutoConfigureMockMvc
public class FooBarControllerTest {

  @Autowired
  private MockMvc mockMvc;

  //User agent string
  private static final String USER_AGENT =
    "Mozilla/5.0 (iPhone; CPU iPhone OS 13_0 like Mac OS X) " +
    "AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0 " +
    "Mobile/15E148 Safari/604.1";

  @Test
  public void testTopPage() throws Exception {
    this.mockMvc.perform(
      //Access with GET method
      get("/")
      //Specify request header
      .header(HttpHeaders.USER_AGENT, USER_AGENT))
      //Test HTTP status code
      .andExpect(status().is2xxSuccessful())
      //Test view name
      .andExpect(view().name("index"))
      //Test model attributes
      .andExpect(model().attribute("userName", "Alice"))
      //Test Content Type
      .andExpect(content().contentType("text/html;charset=UTF-8"))
      //Test if the page contains the specified text
      .andExpect(content().string(containsString("Alice")));
  }
}

Reference material

Recommended Posts

Sample code to unit test a Spring Boot controller with MockMvc
How to write a unit test for Spring Boot 2
Test controller with Mock MVC in Spring Boot
[JUnit 5] Write a validation test with Spring Boot! [Parameterization test]
I wrote a test with Spring Boot + JUnit 5 now
From creating a Spring Boot project to running an application with VS Code
What I was addicted to when developing a Spring Boot application with VS Code
How to unit test Spring AOP
Write test code in Spring Boot
Spring Boot programming with VS Code
Test Spring framework controller with Junit
What to do if you get a "302" error in your controller unit test code in Rails
How to create your own Controller corresponding to / error with Spring Boot
[With sample code] Basics of Spring JDBC to learn with Blog app
Let's write a test code for login function in Spring Boot
Perform transaction confirmation test with Spring Boot
I want to write a unit test!
Try using Spring Boot with VS Code
Form class validation test with Spring Boot
[SpringBoot] How to write a controller test
[Rspec] Flow from introducing Rspec to writing unit test code for a model
Introduction to Java development environment & Spring Boot application created with VS Code
Create a website with Spring Boot + Gradle (jdk1.8.x)
About designing Spring Boot and unit test environment
Create a simple search app with Spring Boot
How to use MyBatis2 (iBatis) with Spring Boot 1.4 (Spring 4)
How to use built-in h2db with spring boot
Try to implement login function with Spring Boot
How to add a classpath in Spring Boot
Transition to a view controller with Swift WebKit
Model unit test code to check uniqueness constraints
How to write test code with Basic authentication
Try to automate migration with Spring Boot Flyway
[Java] Article to add validation with Spring Boot 2.3.1.
I wanted to gradle spring boot with multi-project
Create Spring Boot environment with Windows + VS Code
Create a web api server with spring boot
[Introduction to Spring Boot] Authentication function with Spring Security
Create a Spring Boot development environment with docker
03. I sent a request from Spring Boot to the zip code search API
How to perform UT with Excel as test data with Spring Boot + JUnit5 + DBUnit
[Spring sample code included] How to create a form and how to get multiple records
I tried to clone a web application full of bugs with Spring Boot
Sample to batch process data on DB with Apache Camel Spring Boot starters
Settings for connecting to MySQL with Spring Boot + Spring JDBC
Json Request in Unit Test of Controller using MockMvc
Automatically map DTOs to entities with Spring Boot API
How to unit test with JVM with source using RxAndroid
A memo that I was addicted to when making batch processing with Spring Boot
A memorandum of addiction to Spring Boot2 x Doma2
How to create a Spring Boot project in IntelliJ
[Spring Boot] How to create a project (for beginners)
[Introduction to Spring Boot] Submit a form using thymeleaf
A memorandum when creating a REST service with Spring Boot
Create a simple demo site with Spring Security with Spring Boot 2.1
How to boot by environment with Spring Boot of Maven
Unit test with Junit.
A story that stumbled when deploying a web application created with Spring Boot to EC2
Attempt to SSR Vue.js with Spring Boot and GraalJS
Download with Spring Boot
Port C code with a lot of typecasts to Swift