MST

星途 面试题库

面试题:Java之Spring Boot测试框架基础

在Spring Boot项目中,如何使用JUnit 5和Spring Boot Test来测试一个简单的Controller?请描述主要步骤并给出关键代码示例。
20.2万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试
  1. 添加依赖: 在pom.xml中添加JUnit 5和Spring Boot Test相关依赖。
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-api</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-engine</artifactId>
    <scope>test</scope>
</dependency>
  1. 创建测试类: 假设Controller类为HelloController,创建测试类HelloControllerTest
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;
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.status;

@WebMvcTest(HelloController.class)
public class HelloControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void testGetHello() throws Exception {
        mockMvc.perform(get("/hello"))
              .andExpect(status().isOk())
              .andExpect(content().string("Hello, World!"));
    }
}
  1. 注解说明
    • @WebMvcTest:该注解用于测试Spring MVC控制器。它会自动配置MockMvc,并且只加载与Web MVC相关的组件,而不会加载整个应用上下文,大大提高测试速度。
    • @Autowired:用于注入MockMvc实例,MockMvc提供了一套便捷的API用于模拟HTTP请求并验证响应。
  2. 测试方法说明
    • mockMvc.perform(get("/hello")):使用MockMvc模拟发送一个HTTP GET请求到/hello路径。
    • .andExpect(status().isOk()):验证响应状态码为200(OK)。
    • .andExpect(content().string("Hello, World!")):验证响应内容为Hello, World!

注意,以上示例中的/hello路径和Hello, World!响应内容需根据实际的HelloController实现进行调整。