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 请求到 `/

相关推荐
风流倜傥唐伯虎7 小时前
Spring Boot Jar包生产级启停脚本
java·运维·spring boot
fuquxiaoguang8 小时前
深入浅出:使用MDC构建SpringBoot全链路请求追踪系统
java·spring boot·后端·调用链分析
毕设源码_廖学姐9 小时前
计算机毕业设计springboot招聘系统网站 基于SpringBoot的在线人才对接平台 SpringBoot驱动的智能求职与招聘服务网
spring boot·后端·课程设计
顾北129 小时前
MCP服务端开发:图片搜索助力旅游计划
java·spring boot·dubbo
昀贝9 小时前
IDEA启动SpringBoot项目时报错:命令行过长
java·spring boot·intellij-idea
indexsunny10 小时前
互联网大厂Java面试实战:Spring Boot微服务在电商场景中的应用与挑战
java·spring boot·redis·微服务·kafka·spring security·电商
Coder_Boy_11 小时前
基于SpringAI的在线考试系统-相关技术栈(分布式场景下事件机制)
java·spring boot·分布式·ddd
MX_935911 小时前
Spring的bean工厂后处理器和Bean后处理器
java·后端·spring
程序员泠零澪回家种桔子12 小时前
Spring AI框架全方位详解
java·人工智能·后端·spring·ai·架构
韩立学长14 小时前
基于Springboot泉州旅游攻略平台d5h5zz02(程序、源码、数据库、调试部署方案及开发环境)系统界面展示及获取方式置于文档末尾,可供参考。
数据库·spring boot·旅游