SpringBoot单元测试

SpringBoot 提供了对单元测试的内置支持,使得开发者能够轻松地编写和执行单元测试。在 SpringBoot 项目中,我们通常使用 JUnit 框架进行单元测试,并且配合 Mockito 或 Spring TestContext Framework 等工具来模拟依赖项或注入 Spring 管理的 bean。

以下是一个 SpringBoot 单元测试的详细代码介绍:

首先,我们需要确保项目的 pom.xmlbuild.gradle 文件中包含了以下依赖:

对于 Maven 项目:

xml 复制代码
<dependencies>
    <!-- Spring Boot Test Starter -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    
    <!-- 如果你需要使用 Mockito,则添加以下依赖 -->
    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

对于 Gradle 项目:

gradle 复制代码
dependencies {
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testImplementation 'org.mockito:mockito-core'
}

test {
    useJUnitPlatform()
}

假设我们有一个简单的 SpringBoot 控制器 HelloController

java 复制代码
@RestController
public class HelloController {

    private final HelloService helloService;

    @Autowired
    public HelloController(HelloService helloService) {
        this.helloService = helloService;
    }

    @GetMapping("/hello")
    public String hello() {
        return helloService.sayHello();
    }
}

以及对应的服务 HelloService

java 复制代码
@Service
public class HelloService {

    public String sayHello() {
        return "Hello, World!";
    }
}

现在,我们可以编写一个单元测试类来测试 HelloController

java 复制代码
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;

import static org.mockito.Mockito.when;
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;

@ExtendWith(MockitoExtension.class)
@WebMvcTest(HelloController.class) // 仅加载与 Web 层相关的组件
public class HelloControllerTest {

    @Mock // 创建一个 HelloService 的模拟对象
    private HelloService helloService;

    @InjectMocks // 将模拟的 HelloService 注入到 HelloController 中
    private HelloController helloController;

    @Autowired // 自动注入 MockMvc 对象,用于发送 HTTP 请求并验证响应
    private MockMvc mockMvc;

    @Test
    public void testHello() throws Exception {
        // 设置当调用 sayHello 方法时返回的值
        when(helloService.sayHello()).thenReturn("Hello, Test!");

        // 发送 GET 请求到 /hello 端点
        mockMvc.perform(get("/hello"))
                // 验证响应状态码为 200
                .andExpect(status().isOk())
                // 验证响应内容是否为 "Hello, Test!"
                .andExpect(content().string("Hello, Test!"));
    }
}

在上面的代码中,我们使用了 @WebMvcTest 注解来仅加载与 Web 层相关的组件,这有助于加快测试速度。@Mock 注解用于创建一个 HelloService 的模拟对象,@InjectMocks 注解用于将模拟的 HelloService 注入到 HelloController 中。MockMvc 对象则用于发送 HTTP 请求并验证响应。

testHello 方法中,我们设置了当调用 helloService.sayHello() 方法时应该返回的值,并发送了一个 GET 请求到 `/

相关推荐
【D'accumulation】4 分钟前
令牌主动失效机制范例(利用redis)注释分析
java·spring boot·redis·后端
2401_8543910814 分钟前
高效开发:SpringBoot网上租赁系统实现细节
java·spring boot·后端
wxin_VXbishe23 分钟前
springboot合肥师范学院实习实训管理系统-计算机毕业设计源码31290
java·spring boot·python·spring·servlet·django·php
OEC小胖胖37 分钟前
Spring Boot + MyBatis 项目中常用注解详解(万字长篇解读)
java·spring boot·后端·spring·mybatis·web
2401_857617621 小时前
SpringBoot校园资料平台:开发与部署指南
java·spring boot·后端
quokka561 小时前
Springboot 整合 logback 日志框架
java·spring boot·logback
计算机学姐1 小时前
基于SpringBoot+Vue的在线投票系统
java·vue.js·spring boot·后端·学习·intellij-idea·mybatis
落落落sss1 小时前
MybatisPlus
android·java·开发语言·spring·tomcat·rabbitmq·mybatis
2401_854391082 小时前
Spring Boot大学生就业招聘系统的开发与部署
java·spring boot·后端
杨荧3 小时前
【JAVA开源】基于Vue和SpringBoot的洗衣店订单管理系统
java·开发语言·vue.js·spring boot·spring cloud·开源