当前位置:   article > 正文

Spring Boot单元测试快速入门Demo

Spring Boot单元测试快速入门Demo

1.test介绍

软件测试是一个应用软件质量的保证。开发者开发接口往往忽视接口单元测试。如果会Mock单元测试,那么你的bug量将会大大降低。spring提供test测试模块。整体上,Spring Boot Test支持的测试种类,大致可以分为如下三类:

  • 单元测试:一般面向方法,编写一般业务代码时,测试成本较大。涉及到的注解有@Test。

  • 切片测试:一般面向难于测试的边界功能,介于单元测试和功能测试之间。涉及到的注解有@RunWith @WebMvcTest等。

  • 功能测试:一般面向某个完整的业务功能,同时也可以使用切面测试中的mock能力,推荐使用。涉及到的注解有@RunWith @SpringBootTest等。

功能测试过程中的几个关键要素及支撑方式如下:

  • 测试运行环境:通过@RunWith 和 @SpringBootTest启动spring容器。

  • mock能力:Mockito提供了强大mock功能。

  • 断言能力:AssertJ、Hamcrest、JsonPath提供了强大的断言能力。

2.代码工程

实验目的:验证cotroller和service层逻辑

pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <parent>
  6. <artifactId>springboot-demo</artifactId>
  7. <groupId>com.et</groupId>
  8. <version>1.0-SNAPSHOT</version>
  9. </parent>
  10. <modelVersion>4.0.0</modelVersion>
  11. <artifactId>test</artifactId>
  12. <properties>
  13. <maven.compiler.source>8</maven.compiler.source>
  14. <maven.compiler.target>8</maven.compiler.target>
  15. </properties>
  16. <dependencies>
  17. <dependency>
  18. <groupId>org.springframework.boot</groupId>
  19. <artifactId>spring-boot-starter-web</artifactId>
  20. </dependency>
  21. <dependency>
  22. <groupId>org.springframework.boot</groupId>
  23. <artifactId>spring-boot-autoconfigure</artifactId>
  24. </dependency>
  25. <dependency>
  26. <groupId>org.springframework.boot</groupId>
  27. <artifactId>spring-boot-starter-test</artifactId>
  28. <scope>test</scope>
  29. </dependency>
  30. </dependencies>
  31. </project>

配置文件

  1. server:
  2. port: 8088
  3. username: default
  1. server:
  2. port: 8088
  3. username: dev

cotroller

  1. package com.et.test.controller;
  2. import org.springframework.stereotype.Controller;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import org.springframework.web.bind.annotation.ResponseBody;
  5. import java.util.HashMap;
  6. import java.util.Map;
  7. @Controller
  8. public class HelloWorldController {
  9. @RequestMapping("/hello")
  10. @ResponseBody
  11. public Map<String, Object> showHelloWorld(){
  12. Map<String, Object> map = new HashMap<>();
  13. map.put("msg", "HelloWorld");
  14. return map;
  15. }
  16. }

service

 
 
  1. package com.et.test.service;
  2. import org.springframework.stereotype.Service;
  3. /**
  4. * @ClassName UserService
  5. * @Description TODO
  6. * @Author liuhaihua
  7. * @Date 2024/4/4 13:13
  8. * @Version 1.0
  9. */
  10. public interface UserService {
  11. public String getUserName();
  12. }
  1. package com.et.test.service;
  2. import org.springframework.beans.factory.annotation.Value;
  3. import org.springframework.stereotype.Service;
  4. /**
  5. * @ClassName UserServiceImpl
  6. * @Description TODO
  7. * @Author liuhaihua
  8. * @Date 2024/4/4 13:16
  9. * @Version 1.0
  10. */
  11. @Service
  12. public class UserServiceImpl implements UserService{
  13. @Value("${server.username}")
  14. private String username;
  15. @Override
  16. public String getUserName() {
  17. return username;
  18. }
  19. }

DemoApplication.java

  1. package com.et.test;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. @SpringBootApplication
  5. public class DemoApplication {
  6. public static void main(String[] args) {
  7. SpringApplication.run(DemoApplication.class, args);
  8. }
  9. }

以上只是一些关键代码,所有代码请参见下面代码仓库

代码仓库

  • https://github.com/Harries/springboot-demo

3.测试

验证环境绑定

@ActiveProfiles("dev")

可以切换不同的环境,在同的环境上测试

验证controller功能

  1. @Test
  2. public void bookApiTest() throws Exception {
  3. // mockbean start
  4. userServiceMockBean();
  5. // mockbean end
  6. String expect = "{\"msg\":\"HelloWorld\"}";
  7. mockMvc.perform(MockMvcRequestBuilders.get("/hello"))
  8. .andExpect(MockMvcResultMatchers.content().json(expect))
  9. .andDo(MockMvcResultHandlers.print());
  10. // mockbean reset
  11. }

验证service功能

  1. @Test
  2. public void execute() {
  3. userServiceMockBean();
  4. log.info("username:"+userService.getUserName());
  5. Assertions.assertThat(userService.getUserName().equals("mockname"));
  6. }

下面是完整的测试代码,感兴趣的可以去测试一下

  1. package com.et.test;
  2. import com.et.test.service.UserService;
  3. import org.assertj.core.api.Assertions;
  4. import org.junit.After;
  5. import org.junit.Before;
  6. import org.junit.Test;
  7. import org.junit.runner.RunWith;
  8. import org.mockito.BDDMockito;
  9. import org.slf4j.Logger;
  10. import org.slf4j.LoggerFactory;
  11. import org.springframework.beans.factory.annotation.Autowired;
  12. import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
  13. import org.springframework.boot.test.context.SpringBootTest;
  14. import org.springframework.boot.test.mock.mockito.MockBean;
  15. import org.springframework.test.context.ActiveProfiles;
  16. import org.springframework.test.context.junit4.SpringRunner;
  17. import org.springframework.test.web.servlet.MockMvc;
  18. import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
  19. import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
  20. import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
  21. import javax.annotation.Resource;
  22. @RunWith(SpringRunner.class)
  23. @SpringBootTest(classes = DemoApplication.class)
  24. @ActiveProfiles("dev")
  25. @AutoConfigureMockMvc
  26. public class DemoTests {
  27. private Logger log = LoggerFactory.getLogger(getClass());
  28. @Resource
  29. private MockMvc mockMvc;
  30. //@Autowired
  31. @MockBean
  32. UserService userService;
  33. @Before
  34. public void before() {
  35. log.info("init some data");
  36. }
  37. @After
  38. public void after(){
  39. log.info("clean some data");
  40. }
  41. @Test
  42. public void execute() {
  43. userServiceMockBean();
  44. log.info("username:"+userService.getUserName());
  45. Assertions.assertThat(userService.getUserName().equals("mockname"));
  46. }
  47. @Test
  48. public void bookApiTest() throws Exception {
  49. // mockbean start
  50. userServiceMockBean();
  51. // mockbean end
  52. String expect = "{\"msg\":\"HelloWorld\"}";
  53. mockMvc.perform(MockMvcRequestBuilders.get("/hello"))
  54. .andExpect(MockMvcResultMatchers.content().json(expect))
  55. .andDo(MockMvcResultHandlers.print());
  56. // mockbean reset
  57. }
  58. public void userServiceMockBean() {
  59. BDDMockito.given(userService.getUserName()).willReturn("mockname");
  60. }
  61. }

4.引用

  • https://spring.io/guides/gs/testing-web

  • http://www.liuhaihua.cn/archives/710395.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/393449
推荐阅读
相关标签
  

闽ICP备14008679号