学习如何使用本教程中提供的工具,并在 Spring Boot 环境中编写单元测试和集成测试。

本文中,我们将了解如何编写单元测试并将其集成在 Spring Boot 环境中。你可在网上找到大量关于这个主题的教程,但很难在一个页面中找到你需要的所有信息。我经常注意到初级开发人员混淆了单元测试和集成测试的概念,特别是在谈到 Spring 生态系统时。我将尝试讲清楚不同注解在不同上下文中的用法。

维基百科是这么说 单元测试 的:

在计算机编程中,单元测试是一种软件测试方法,用以测试源代码的单个单元、一个或多个计算机程序模块的集合以及相关的控制数据、使用过程和操作过程,以确定它们是否适合使用。

集成测试

“集成测试(有时也称集成和测试,缩写为 I&T)是软件测试的一个阶段,在这个阶段中,各个软件模块被组合在一起来进行测试。”

简而言之,当我们在做单元测试时,只是测试了一个代码单元,每次只测试一个方法,不包括与正测试组件相交互的其他所有组件。

另一方面,在集成测试中,我们测试各组件之间的集成。由于单元测试,我们可知这些组件行为与所需一致,但不清楚它们是如何在一起工作的。这就是集成测试的职责。

所有 Java 开发者都知道 JUnit 是执行单元测试的主要框架。它提供了许多注解来对期望进行断言。

Hamcrest 是一个用于软件测试的附加框架。Hamcrest 允许使用现有的 matcher 类来检查代码中的条件,还允许自定义 matcher 实现。要在 JUnit 中使用 Hamcrest matcher,必须使用 assertThat 语句,后跟一个或多个 matcher。

在这里,你可以看到使用这两种框架的简单测试:

  1. import static org.hamcrest.CoreMatchers.allOf;
  2. import static org.hamcrest.CoreMatchers.anyOf;
  3. import static org.hamcrest.CoreMatchers.both;
  4. import static org.hamcrest.CoreMatchers.containsString;
  5. import static org.hamcrest.CoreMatchers.equalTo;
  6. import static org.hamcrest.CoreMatchers.everyItem;
  7. import static org.hamcrest.CoreMatchers.hasItems;
  8. import static org.hamcrest.CoreMatchers.not;
  9. import static org.hamcrest.CoreMatchers.sameInstance;
  10. import static org.hamcrest.CoreMatchers.startsWith;
  11. import static org.junit.Assert.assertArrayEquals;
  12. import static org.junit.Assert.assertEquals;
  13. import static org.junit.Assert.assertFalse;
  14. import static org.junit.Assert.assertNotNull;
  15. import static org.junit.Assert.assertNotSame;
  16. import static org.junit.Assert.assertNull;
  17. import static org.junit.Assert.assertSame;
  18. import static org.junit.Assert.assertThat;
  19. import static org.junit.Assert.assertTrue;
  20. import java.util.Arrays;
  21. import org.hamcrest.core.CombinableMatcher;
  22. import org.junit.Test;
  23. public class AssertTests {
  24. @Test
  25. public void testAssertArrayEquals() {
  26. byte[] expected = "trial".getBytes();
  27. byte[] actual = "trial".getBytes();
  28. assertArrayEquals("failure - byte arrays not same", expected, actual);
  29. }
  30. @Test
  31. public void testAssertEquals() {
  32. assertEquals("failure - strings are not equal", "text", "text");
  33. }
  34. @Test
  35. public void testAssertFalse() {
  36. assertFalse("failure - should be false", false);
  37. }
  38. @Test
  39. public void testAssertNotNull() {
  40. assertNotNull("should not be null", new Object());
  41. }
  42. @Test
  43. public void testAssertNotSame() {
  44. assertNotSame("should not be same Object", new Object(), new Object());
  45. }
  46. @Test
  47. public void testAssertNull() {
  48. assertNull("should be null", null);
  49. }
  50. @Test
  51. public void testAssertSame() {
  52. Integer aNumber = Integer.valueOf(768);
  53. assertSame("should be same", aNumber, aNumber);
  54. }
  55. // JUnit Matchers assertThat
  56. @Test
  57. public void testAssertThatBothContainsString() {
  58. assertThat("albumen", both(containsString("a")).and(containsString("b")));
  59. }
  60. @Test
  61. public void testAssertThatHasItems() {
  62. assertThat(Arrays.asList("one", "two", "three"), hasItems("one", "three"));
  63. }
  64. @Test
  65. public void testAssertThatEveryItemContainsString() {
  66. assertThat(Arrays.asList(new String[] { "fun", "ban", "net" }), everyItem(containsString("n")));
  67. }
  68. // Core Hamcrest Matchers with assertThat
  69. @Test
  70. public void testAssertThatHamcrestCoreMatchers() {
  71. assertThat("good", allOf(equalTo("good"), startsWith("good")));
  72. assertThat("good", not(allOf(equalTo("bad"), equalTo("good"))));
  73. assertThat("good", anyOf(equalTo("bad"), equalTo("good")));
  74. assertThat(7, not(CombinableMatcher.<Integer> either(equalTo(3)).or(equalTo(4))));
  75. assertThat(new Object(), not(sameInstance(new Object())));
  76. }
  77. @Test
  78. public void testAssertTrue() {
  79. assertTrue("failure - should be true", true);
  80. }
  81. }

让我们来写一个简单的程序吧。其目的是为漫画提供一个基本的搜索引擎。

Kenshiro vs Roul

首先,需要添加一些依赖到我们的工程中。

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-test</artifactId>
  4. <scope>test</scope>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-starter-web</artifactId>
  9. </dependency>
  10. <dependency>
  11. <groupId>org.projectlombok</groupId>
  12. <artifactId>lombok</artifactId>
  13. <version>1.16.20</version>
  14. <scope>provided</scope>
  15. </dependency>

我们的模型非常简单,只有两个类组成:Manga 和 MangaResult

Manga 类表示系统检索到的 Manga 实例。使用 Lombok 来减少样板代码。

  1. package com.mgiglione.model;
  2. import lombok.AllArgsConstructor;
  3. import lombok.Builder;
  4. import lombok.Getter;
  5. import lombok.NoArgsConstructor;
  6. import lombok.Setter;
  7. @Getter @Setter @NoArgsConstructor @AllArgsConstructor @Builder
  8. public class Manga {
  9. private String title;
  10. private String description;
  11. private Integer volumes;
  12. private Double score;
  13. }

MangaResult 类是包含了一个 Manga List 的包装类。

  1. package com.mgiglione.model;
  2. import java.util.List;
  3. import lombok.Getter;
  4. import lombok.NoArgsConstructor;
  5. import lombok.Setter;
  6. @Getter @Setter @NoArgsConstructor
  7. public class MangaResult {
  8. private List<Manga> result;
  9. }

为实现本 Service,我们将使用由 Jikan Moe 提供的免费 API 接口。

RestTemplate 是用来对 API 进行发起 REST 调用的 Spring 类。

  1. package com.mgiglione.service;
  2. import java.util.List;
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Service;
  7. import org.springframework.web.client.RestTemplate;
  8. import com.mgiglione.model.Manga;
  9. import com.mgiglione.model.MangaResult;
  10. @Service
  11. public class MangaService {
  12. Logger logger = LoggerFactory.getLogger(MangaService.class);
  13. private static final String MANGA_SEARCH_URL="http://api.jikan.moe/search/manga/";
  14. @Autowired
  15. RestTemplate restTemplate;
  16. public List<Manga> getMangasByTitle(String title) {
  17. return restTemplate.getForEntity(MANGA_SEARCH_URL+title, MangaResult.class).getBody().getResult();
  18. }
  19. }

下一步就是写一个暴露了两个端点的 REST Controller,一个是同步的,一个是异步的,其仅用于测试目的。该 Controller 使用了上面定义的 Service。

  1. package com.mgiglione.controller;
  2. import java.util.List;
  3. import java.util.concurrent.CompletableFuture;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.scheduling.annotation.Async;
  8. import org.springframework.web.bind.annotation.PathVariable;
  9. import org.springframework.web.bind.annotation.RequestMapping;
  10. import org.springframework.web.bind.annotation.RequestMethod;
  11. import org.springframework.web.bind.annotation.ResponseBody;
  12. import org.springframework.web.bind.annotation.RestController;
  13. import com.mgiglione.model.Manga;
  14. import com.mgiglione.service.MangaService;
  15. @RestController
  16. @RequestMapping(value = "/manga")
  17. public class MangaController {
  18. Logger logger = LoggerFactory.getLogger(MangaController.class);
  19. @Autowired
  20. private MangaService mangaService;
  21. @RequestMapping(value = "/async/{title}", method = RequestMethod.GET)
  22. @Async
  23. public CompletableFuture<List<Manga>> searchASync(@PathVariable(name = "title") String title) {
  24. return CompletableFuture.completedFuture(mangaService.getMangasByTitle(title));
  25. }
  26. @RequestMapping(value = "/sync/{title}", method = RequestMethod.GET)
  27. public @ResponseBody <List<Manga>> searchSync(@PathVariable(name = "title") String title) {
  28. return mangaService.getMangasByTitle(title);
  29. }
  30. }
  1. mvn spring-boot:run

然后,Let’s try it:

  1. curl http://localhost:8080/manga/async/ken
  2. curl http://localhost:8080/manga/sync/ken

示例输出:

  1. {
  2. "title":"Rurouni Kenshin: Meiji Kenkaku Romantan",
  3. "description":"Ten years have passed since the end of Bakumatsu, an era of war that saw the uprising of citizens against the Tokugawa shogunate. The revolutionaries wanted to create a time of peace, and a thriving c...",
  4. "volumes":28,
  5. "score":8.69
  6. },
  7. {
  8. "title":"Sun-Ken Rock",
  9. "description":"The story revolves around Ken, a man from an upper-class family that was orphaned young due to his family's involvement with the Yakuza; he became a high school delinquent known for fighting. The only...",
  10. "volumes":25,
  11. "score":8.12
  12. },
  13. {
  14. "title":"Yumekui Kenbun",
  15. "description":"For those who suffer nightmares, help awaits at the Ginseikan Tea House, where patrons can order much more than just Darjeeling. Hiruko is a special kind of a private investigator. He's a dream eater....",
  16. "volumes":9,
  17. "score":7.97
  18. }

Spring Boot 提供了一个强大的类以使测试变得简单:@SpringBootTest 注解

可以在基于 Spring Boot 运行的测试类上指定此注解。

除常规 Spring TestContext Framework 之外,其还提供以下功能:

  • 当 @ContextConfiguration (loader=…) 没有特别声明时,使用 SpringBootContextLoader 作为默认 ContextLoader。
  • 在未使用嵌套的 @Configuration 注解,且未显式指定相关类时,自动搜索 @SpringBootConfiguration。
  • 允许使用 Properties 来自定义 Environment 属性。
  • 对不同的 Web 环境模式提供支持,包括启动在已定义或随机端口上的完全运行的 Web 服务器的功能。
  • 注册 TestRestTemplate 和 / 或 WebTestClient Bean,以便在完全运行在 Web 服务器上的 Web 测试中使用。

此处,我们仅有两个组件需要测试:MangaService 和 MangaController

为了测试 MangaService,我们需要将其与外部组件隔离开来。本例中,只需要一个外部组件:RestTemplate,我们用它来调用远程 API。

我们需要做的是模拟 RestTemplate Bean,并让它始终以固定的给定响应进行响应。Spring Test 结合并扩展了 Mockito 库,通过 @MockBean 注解,我们可以配置模拟 Bean。

  1. package com.mgiglione.service.test.unit;
  2. import static org.mockito.ArgumentMatchers.any;
  3. import static org.mockito.Mockito.when;
  4. import java.io.IOException;
  5. import java.util.List;
  6. import org.junit.Test;
  7. import org.junit.runner.RunWith;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.boot.test.context.SpringBootTest;
  10. import org.springframework.boot.test.mock.mockito.MockBean;
  11. import org.springframework.http.HttpStatus;
  12. import org.springframework.http.ResponseEntity;
  13. import org.springframework.test.context.junit4.SpringRunner;
  14. import org.springframework.web.client.RestTemplate;
  15. import static org.assertj.core.api.Assertions.assertThat;
  16. import com.mgiglione.model.Manga;
  17. import com.mgiglione.model.MangaResult;
  18. import com.mgiglione.service.MangaService;
  19. import com.mgiglione.utils.JsonUtils;
  20. @RunWith(SpringRunner.class)
  21. @SpringBootTest
  22. public class MangaServiceUnitTest {
  23. @Autowired
  24. private MangaService mangaService;
  25. // MockBean is the annotation provided by Spring that wraps mockito one
  26. // Annotation that can be used to add mocks to a Spring ApplicationContext.
  27. // If any existing single bean of the same type defined in the context will be replaced by the mock, if no existing bean is defined a new one will be added.
  28. @MockBean
  29. private RestTemplate template;
  30. @Test
  31. public void testGetMangasByTitle() throws IOException {
  32. // Parsing mock file
  33. MangaResult mRs = JsonUtils.jsonFile2Object("ken.json", MangaResult.class);
  34. // Mocking remote service
  35. when(template.getForEntity(any(String.class), any(Class.class))).thenReturn(new ResponseEntity(mRs, HttpStatus.OK));
  36. // I search for goku but system will use mocked response containing only ken, so I can check that mock is used.
  37. List<Manga> mangasByTitle = mangaService.getMangasByTitle("goku");
  38. assertThat(mangasByTitle).isNotNull()
  39. .isNotEmpty()
  40. .allMatch(p -> p.getTitle()
  41. .toLowerCase()
  42. .contains("ken"));
  43. }
  44. }

正如在 MangaService 的单元测试中所做的那样,我们需要隔离组件。在这种情况下,我们需要模拟 MangaService Bean。

然后,我们还有一个问题……Controller 部分是管理 HttpRequest 的系统的一部分,因此我们需要一个系统来模拟这种行为,而非启动完整的 HTTP 服务器。

MockMvc 是执行该操作的 Spring 类。其可以以不同的方式进行设置:

  1. 使用 Standalone Context
  2. 使用 WebApplication Context
  3. 让 Spring 通过在测试类上使用 @SpringBootTest、@AutoConfigureMockMvc 这些注解来加载所有的上下文,以实现自动装配
  4. 让 Spring 通过在测试类上使用 @WebMvcTest 注解来加载 Web 层上下文,以实现自动装配
  1. package com.mgiglione.service.test.unit;
  2. import static org.hamcrest.Matchers.is;
  3. import static org.mockito.ArgumentMatchers.any;
  4. import static org.mockito.Mockito.when;
  5. import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch;
  6. import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
  7. import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
  8. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
  9. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request;
  10. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
  11. import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
  12. import java.util.ArrayList;
  13. import java.util.List;
  14. import org.junit.Before;
  15. import org.junit.Test;
  16. import org.junit.runner.RunWith;
  17. import org.springframework.beans.factory.annotation.Autowired;
  18. import org.springframework.boot.test.context.SpringBootTest;
  19. import org.springframework.boot.test.mock.mockito.MockBean;
  20. import org.springframework.http.MediaType;
  21. import org.springframework.test.context.junit4.SpringRunner;
  22. import org.springframework.test.web.servlet.MockMvc;
  23. import org.springframework.test.web.servlet.MvcResult;
  24. import org.springframework.web.context.WebApplicationContext;
  25. import com.mgiglione.controller.MangaController;
  26. import com.mgiglione.model.Manga;
  27. import com.mgiglione.service.MangaService;
  28. @SpringBootTest
  29. @RunWith(SpringRunner.class)
  30. public class MangaControllerUnitTest {
  31. MockMvc mockMvc;
  32. @Autowired
  33. protected WebApplicationContext wac;
  34. @Autowired
  35. MangaController mangaController;
  36. @MockBean
  37. MangaService mangaService;
  38. /**
  39. * List of samples mangas
  40. */
  41. private List<Manga> mangas;
  42. @Before
  43. public void setup() throws Exception {
  44. this.mockMvc = standaloneSetup(this.mangaController).build();// Standalone context
  45. // mockMvc = MockMvcBuilders.webAppContextSetup(wac)
  46. // .build();
  47. Manga manga1 = Manga.builder()
  48. .title("Hokuto no ken")
  49. .description("The year is 199X. The Earth has been devastated by nuclear war...")
  50. .build();
  51. Manga manga2 = Manga.builder()
  52. .title("Yumekui Kenbun")
  53. .description("For those who suffer nightmares, help awaits at the Ginseikan Tea House, where patrons can order much more than just Darjeeling. Hiruko is a special kind of a private investigator. He's a dream eater....")
  54. .build();
  55. mangas = new ArrayList<>();
  56. mangas.add(manga1);
  57. mangas.add(manga2);
  58. }
  59. @Test
  60. public void testSearchSync() throws Exception {
  61. // Mocking service
  62. when(mangaService.getMangasByTitle(any(String.class))).thenReturn(mangas);
  63. mockMvc.perform(get("/manga/sync/ken").contentType(MediaType.APPLICATION_JSON))
  64. .andExpect(status().isOk())
  65. .andExpect(jsonPath("$[0].title", is("Hokuto no ken")))
  66. .andExpect(jsonPath("$[1].title", is("Yumekui Kenbun")));
  67. }
  68. @Test
  69. public void testSearchASync() throws Exception {
  70. // Mocking service
  71. when(mangaService.getMangasByTitle(any(String.class))).thenReturn(mangas);
  72. MvcResult result = mockMvc.perform(get("/manga/async/ken").contentType(MediaType.APPLICATION_JSON))
  73. .andDo(print())
  74. .andExpect(request().asyncStarted())
  75. .andDo(print())
  76. // .andExpect(status().is2xxSuccessful()).andReturn();
  77. .andReturn();
  78. // result.getRequest().getAsyncContext().setTimeout(10000);
  79. mockMvc.perform(asyncDispatch(result))
  80. .andDo(print())
  81. .andExpect(status().isOk())
  82. .andExpect(jsonPath("$[0].title", is("Hokuto no ken")));
  83. }
  84. }

正如在代码中所看到的那样,选择第一种解决方案是因为其是最轻量的一个,并且我们可以对 Spring 上下文中加载的对象有更好的治理。

在异步测试中,必须首先通过调用服务,然后启动 asyncDispatch 方法来模拟异步行为。

对于集成测试,我们希望提供下游通信来检查我们的主要组件。

这个测试也是非常简单的。我们不需要模拟任何东西,因为我们的目的就是要调用远程 Manga API。

  1. package com.mgiglione.service.test.integration;
  2. import static org.assertj.core.api.Assertions.assertThat;
  3. import java.util.List;
  4. import org.junit.Test;
  5. import org.junit.runner.RunWith;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.boot.test.context.SpringBootTest;
  8. import org.springframework.test.context.junit4.SpringRunner;
  9. import com.mgiglione.model.Manga;
  10. import com.mgiglione.service.MangaService;
  11. @RunWith(SpringRunner.class)
  12. @SpringBootTest
  13. public class MangaServiceIntegrationTest {
  14. @Autowired
  15. private MangaService mangaService;
  16. @Test
  17. public void testGetMangasByTitle() {
  18. List<Manga> mangasByTitle = mangaService.getMangasByTitle("ken");
  19. assertThat(mangasByTitle).isNotNull().isNotEmpty();
  20. }
  21. }

这个测试和单元测试很是相似,但在这个案例中,我们无需再模拟 MangaService。

  1. package com.mgiglione.service.test.integration;
  2. import static org.hamcrest.Matchers.hasItem;
  3. import static org.hamcrest.Matchers.is;
  4. import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch;
  5. import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
  6. import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
  7. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
  8. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request;
  9. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
  10. import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
  11. import org.junit.Before;
  12. import org.junit.Test;
  13. import org.junit.runner.RunWith;
  14. import org.springframework.beans.factory.annotation.Autowired;
  15. import org.springframework.boot.test.context.SpringBootTest;
  16. import org.springframework.http.MediaType;
  17. import org.springframework.test.context.junit4.SpringRunner;
  18. import org.springframework.test.web.servlet.MockMvc;
  19. import org.springframework.test.web.servlet.MvcResult;
  20. import org.springframework.web.context.WebApplicationContext;
  21. import com.mgiglione.controller.MangaController;
  22. @SpringBootTest
  23. @RunWith(SpringRunner.class)
  24. public class MangaControllerIntegrationTest {
  25. // @Autowired
  26. MockMvc mockMvc;
  27. @Autowired
  28. protected WebApplicationContext wac;
  29. @Autowired
  30. MangaController mangaController;
  31. @Before
  32. public void setup() throws Exception {
  33. this.mockMvc = standaloneSetup(this.mangaController).build();// Standalone context
  34. // mockMvc = MockMvcBuilders.webAppContextSetup(wac)
  35. // .build();
  36. }
  37. @Test
  38. public void testSearchSync() throws Exception {
  39. mockMvc.perform(get("/manga/sync/ken").contentType(MediaType.APPLICATION_JSON))
  40. .andExpect(status().isOk())
  41. .andExpect(jsonPath("$.*.title", hasItem(is("Hokuto no Ken"))));
  42. }
  43. @Test
  44. public void testSearchASync() throws Exception {
  45. MvcResult result = mockMvc.perform(get("/manga/async/ken").contentType(MediaType.APPLICATION_JSON))
  46. .andDo(print())
  47. .andExpect(request().asyncStarted())
  48. .andDo(print())
  49. .andReturn();
  50. mockMvc.perform(asyncDispatch(result))
  51. .andDo(print())
  52. .andExpect(status().isOk())
  53. .andExpect(jsonPath("$.*.title", hasItem(is("Hokuto no Ken"))));
  54. }
  55. }

我们已经了解了在 Spring Boot 环境下单元测试和集成测试的主要不同,了解了像 Hamcrest 这样简化测试编写的框架。当然,也可以在我的 GitHub 仓库 里找到所有代码。

原文:https://dzone.com/articles/unit-and-integration-tests-in-spring-boot-2

作者:Marco Giglione

9月福利,关注公众号

后台回复:004,领取8月翻译集锦!

往期福利回复:001,002, 003即可领取!

img

版权声明:本文为liululee原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/liululee/p/11595537.html