【讲解下Spring Boot单元测试】

🌈个人主页: 程序员不想敲代码啊
🏆CSDN优质创作者,CSDN实力新星,CSDN博客专家
👍点赞⭐评论⭐收藏
🤝希望本文对您有所裨益,如有不足之处,欢迎在评论区提出指正,让我们共同学习、交流进步!

🌠Spring Boot单元测试

🌠Spring Boot提供一个非常方便的方式来写单元测试,它利用了Spring Test中的功能,允许你很容易地测试Spring应用程序中的各个组件。

🌠首先,你需要为你的项目添加Spring Boot Starter Test依赖。对于Maven项目,你需要在pom.xml中添加以下依赖:

xml 复制代码
<dependencies>
    <!-- 其它依赖... -->

    <!-- Spring Boot Starter Test依赖 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

🌠对于Gradle项目,你需要在build.gradle文件中添加以下依赖:

gradle 复制代码
dependencies {
    // 其它依赖...

    // 测试依赖
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

🌠下面提供一个简单的单元测试示例,假设你有一个Spring Boot应用程序中的服务类,我们可以进行单元测试:

java 复制代码
@Service
public class CalculatorService {
    public int add(int a, int b) {
        return a + b;
    }
}

🌠对于上述的CalculatorService类,一个简单的单元测试会是这样的:

java 复制代码
import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;

@SpringBootTest
public class CalculatorServiceTest {

    @Autowired
    private CalculatorService calculatorService;

    @Test
    public void testAdd() {
        // Arrange (准备阶段)
        int numberA = 10;
        int numberB = 20;

        // Act (行动阶段)
        int result = calculatorService.add(numberA, numberB);

        // Assert (断言阶段)
        assertThat(result).isEqualTo(30);
    }
}

🌠在上述例子中,@SpringBootTest注解创建了一个应用程序上下文,这在进行集成测试时是有用的。但如果只是单纯的单元测试一个组件,并不需要完整的上下文,可以用@ExtendWith(SpringExtension.class)代替以提升测试速度。

🌠对于需要测试Spring MVC控制器的情况,你可以使用MockMvc来模拟HTTP请求和断言响应:

java 复制代码
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;

@SpringBootTest
@AutoConfigureMockMvc
public class WebLayerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void shouldReturnDefaultMessage() throws Exception {
        this.mockMvc.perform(get("/"))
                .andExpect(status().isOk())
                .andExpect(content().string("Hello World"));
    }
}

🌠在这个示例中,@AutoConfigureMockMvc@SpringBootTest被用来注入一个MockMvc实例,然后我们使用这个实例来执行一个HTTP GET请求,并断言结果。这种测试方式更接近于真实的HTTP请求,但它依然运行在服务器未启动的情况下。

🌠最后,正确的单元测试不应该依赖Spring框架或是任何外部服务/数据库等,这些是集成测试的范畴。对于单元测试,你应该尽可能地模拟你的依赖,使得每个测试小而快,并只关注一个特定的组件。

相关推荐
创码小奇客3 小时前
Spring Boot 集成 Talos:打造智能调参系统,让模型性能自动飙升
java·spring boot·trae
潘多编程4 小时前
AWS上部署Spring Boot应用的完整指南
spring boot·云计算·aws
Full Stack Developme5 小时前
PostgreSQL dblink 与 Spring Boot @Transactional 的事务整合
数据库·spring boot·postgresql
青灯文案110 小时前
Spring Boot 的事务注解 @Transactional 失效的几种情况
java·spring boot·后端
think12310 小时前
带你走进Spring Cloud的世界
spring boot·后端·spring cloud
泉城老铁11 小时前
Spring Boot 应用打包部署到 Tomcat ,如何极致调优看这里
java·spring boot·后端
NullPointerExpection12 小时前
dify + mcp 实现图片 ocr 识别
spring boot·llm·ocr·springai·deepseek·mcp
℡余晖^13 小时前
每日面试题20:spring和spring boot的区别
java·spring boot·spring
没有bug.的程序员13 小时前
《Spring Boot应用工程化提升:多模块、脚手架与DevTools》
java·运维·spring boot
2025年一定要上岸14 小时前
【Django】-9- 单元测试和集成测试(上)
单元测试·django·集成测试