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

相关推荐
没有bug.的程序员9 分钟前
Spring Boot 事务管理:@Transactional 失效场景、底层内幕与分布式补偿实战终极指南
java·spring boot·分布式·后端·transactional·失效场景·底层内幕
华农第一蒟蒻17 分钟前
一次服务器CPU飙升的排查与解决
java·运维·服务器·spring boot·arthas
闻哥1 小时前
从 AJAX 到浏览器渲染:前端底层原理与性能指标全解析
java·前端·spring boot·ajax·okhttp·面试
短剑重铸之日1 小时前
《SpringCloud实用版》统一认证授权:Spring Authorization Server + OAuth2 + JWT 生产级方案
java·后端·spring·jwt·oauth2
cookqq2 小时前
基于Spring AI+本地大模型+MongoDB实现私密化与记忆能力-企业级免费大模型应用
人工智能·mongodb·spring
卓码软件测评2 小时前
【第三方高校课题软件确认测试:LoadRunner与JMeter-企业级性能测试工具选型深度对比】
测试工具·jmeter·性能优化·单元测试·测试用例
码农阿豪2 小时前
基于Milvus与混合检索的云厂商文档智能问答系统:Java SpringBoot全栈实现
java·spring boot·milvus
哪里不会点哪里.3 小时前
什么是 Spring Cloud?
后端·spring·spring cloud
山上三树3 小时前
详细介绍读写锁
开发语言·c++·spring
树码小子3 小时前
Spring框架:Spring程序快速上手
java·后端·spring