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

目录

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

1.1、引入依赖

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

2、Spring MVC 控制器测试

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

2.2 编写控制器测试类


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

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

1.1 引入依赖

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

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

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 创建控制器及映射方法

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 编写控制器测试类

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 用于数据访问层测试)。

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

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

  • 6
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值