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

相关推荐
深色風信子1 小时前
SpringBoot 集成 LangChain4j RAG Redis 搜索
spring boot·langchain4j rag·rag redis 搜索·rag redis·springboot rag·rag 搜索
小蒜学长2 小时前
springboot餐厅信息管理系统设计(代码+数据库+LW)
java·数据库·spring boot·后端
Jabes.yang2 小时前
Java大厂面试实录:从Spring Boot到微服务的技术探讨
java·spring boot·spring cloud·微服务·技术面试
咖啡Beans3 小时前
SpringBoot集成MongoDB使用
spring boot·mongodb
q_19132846953 小时前
基于RuoYi框架+Mysql的汽车进销存后台管理系统
数据库·vue.js·spring boot·mysql·汽车·个人开发·若依
悟能不能悟4 小时前
springboot在DTO使用service,怎么写
java·数据库·spring boot
__XYZ4 小时前
RedisTemplate 实现分布式锁
java·spring boot·redis·分布式·junit
不能再留遗憾了4 小时前
【SpringCloud】Sentinel
spring·spring cloud·sentinel
Cc00108525 小时前
【AI学习笔记】用AI生成spring boot + redis
spring boot·笔记·学习·ai编程
whltaoin5 小时前
AI 超级智能体全栈项目阶段五:RAG 四大流程详解、最佳实践与调优(基于 Spring AI 实现)
java·人工智能·spring·rag·springai