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

相关推荐
Q_Q5110082855 小时前
python+django/flask的眼科患者随访管理系统 AI智能模型
spring boot·python·django·flask·node.js·php
慧都小项7 小时前
Parasoft C/C++test中Trace32调试器的配置与单元测试执行
单元测试·parasoft·trace32调试器
韩立学长7 小时前
基于Springboot的旧时月历史论坛4099k6s9(程序、源码、数据库、调试部署方案及开发环境)系统界面展示及获取方式置于文档末尾,可供参考。
数据库·spring boot·后端
Q_Q5110082857 小时前
python+django/flask的在线学习系统的设计与实现 积分兑换礼物
spring boot·python·django·flask·node.js·php
葡萄城技术团队8 小时前
迎接下一代 React 框架:Next.js 16 核心能力解读
javascript·spring·react.js
Q_Q5110082858 小时前
python+django/flask的车辆尾气检测排放系统-可视化大屏展示
spring boot·python·django·flask·node.js·php
汤姆yu8 小时前
基于SpringBoot的动漫周边商场系统的设计与开发
java·spring boot·后端
灰小猿9 小时前
Spring前后端分离项目时间格式转换问题全局配置解决
java·前端·后端·spring·spring cloud
摇滚侠10 小时前
Spring Boot3零基础教程,响应式编程的模型,笔记109
java·spring boot·笔记
Q_Q196328847511 小时前
python+django/flask基于Echarts+Python的图书零售监测系统设计与实现(带大屏)
spring boot·python·django·flask·node.js·php