Spring Boot的单元测试及示例代码

目录

[1、单元测试(非 Web 上下文)](#1、单元测试(非 Web 上下文))

1.1、引入依赖

[1.2 编写单元测试类(示例代码)](#1.2 编写单元测试类(示例代码))

[2、Spring MVC 控制器测试](#2、Spring MVC 控制器测试)

2.1、创建控制器及映射方法

[2.2 编写控制器测试类](#2.2 编写控制器测试类)


Spring Boot 提供了强大的单元测试和集成测试支持,以简化基于 Spring 的应用程序的测试。下面分别使用 Spring Boot 进行单元测试Web 控制器(MVC)测试。

**1、**单元测试(非 Web 上下文)

1.1 引入依赖

XML 复制代码
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

1.2 编写单元测试类(示例代码)

java 复制代码
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserServiceTest {

    // 业务服务类Service
    @Autowired
    private UserService userService; 

    @Test
    public void testFindUser() {
        User user = userService.findUserById(1L);
        // 断言检查user对象是否正确
        assertNotNull(user);
        assertEquals("用户名", user.getName());
    }
}

2、Spring MVC 控制器测试

针对 Spring MVC 控制器,Spring Boot 提供了 MockMvc 测试工具来模拟 HTTP 请求,并验证响应。

2.1 创建控制器及映射方法

java 复制代码
package com.example.demo.controller;  
  
import org.springframework.web.bind.annotation.GetMapping;  
import org.springframework.web.bind.annotation.RestController;  
  
@RestController  
public class ExampleController {  
  
    @GetMapping("/hello")  
    public String hello() {  
        return "Hello, World!";  
    }  
}

2.2 编写控制器测试类

java 复制代码
package com.example.demo.controller;  
  
import org.junit.jupiter.api.Test;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;  
import org.springframework.test.web.servlet.MockMvc;  
import org.springframework.test.web.servlet.MvcResult;  
  
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 static org.hamcrest.Matchers.equalTo;  
  
@WebMvcTest(ExampleController.class)  
public class ExampleControllerTest {  
  
    @Autowired  
    private MockMvc mockMvc;  
  
    @Test  
    public void testHello() throws Exception {  
        MvcResult mvcResult = mockMvc.perform(get("/hello"))  
                .andExpect(status().isOk())  
                .andExpect(content().string(equalTo("Hello, World!")))  
                .andReturn();  
  
        String contentAsString = mvcResult.getResponse().getContentAsString();  
        System.out.println(contentAsString); // 输出响应内容,便于调试  
    }  
}

在这个测试类中,我们使用了 @WebMvcTest 注解,它告诉 Spring Test 加载 Spring MVC 的基础配置,但是不会加载整个应用上下文,因此它更适合于测试控制器。@Autowired 注解用于自动注入 MockMvc 实例,它提供了模拟 HTTP 请求并验证响应的功能。

testHello 方法中,我们使用 mockMvc.perform 方法发送一个 GET 请求到 /hello 路径,并使用 andExpect 方法链来验证响应的状态码和内容。如果测试失败,andExpect 方法会抛出异常。

注意:

在实际项目中,你可能还需要编写其他类型的测试,如集成测试、服务层测试、数据访问层测试等,并可能需要配置不同的测试切片(例如 @DataJpaTest 用于数据访问层测试)。

在编写测试时,请确保该测试是可重复的、独立的,并且尽可能地覆盖所有重要的业务逻辑场景。良好的测试实践有助于提高代码质量,并减少在生产环境中出现问题的风险。

后续有时间,再继续更新集成测试、服务层测试、数据访问层测试等。

相关推荐
一起养小猫3 分钟前
LeetCode100天Day4-盛最多水的容器与两数之和II
java·数据结构·算法·leetcode
ZBritney8 分钟前
JAVA中的多线程
java
whn197712 分钟前
达梦数据库的整体负载变化查看
java·开发语言·数据库
小满、12 分钟前
RabbitMQ:Fanout、Direct、Topic 交换机、队列声明与消息转换器
java·分布式·消息队列·rabbitmq·spring amqp
檀越剑指大厂21 分钟前
【Idea系列】换行处理
java·ide·intellij-idea
我一定会有钱31 分钟前
pytest测试框架基础
python·单元测试·自动化·pytest
wanghowie34 分钟前
01.04 Java基础篇|泛型、注解与反射实战
java·开发语言·windows
深圳佛手38 分钟前
Java大对象(如 List、Map)如何复用?错误的方法是?正确的方法是?
java·jvm·windows
言之。42 分钟前
Claude Code Skills 实用使用手册
java·开发语言
苹果醋342 分钟前
JAVA设计模式之策略模式
java·运维·spring boot·mysql·nginx