一起玩转微服务:单元测试

玩技站长
玩技站长
管理员, Keymaster
11056
文章
0
粉丝
测试资讯评论104字数 2927阅读9分45秒阅读模式
摘要作为一名java开发者,相信你或多或少的接触过单元测试,对于测试来讲它是一门能够区分专业开发人员与业余开发人员的重要学科,这篇文章将对java中最常见的一个单元测试框架junit进...

作为一名java开发者,相信你或多或少的接触过单元测试,对于测试来讲它是一门能够区分专业开发人员与业余开发人员的重要学科,这篇文章将对java中最常见的一个单元测试框架junit进行一个梳理和讲解。

为什么需要单元测试文章源自玩技e族-https://www.playezu.com/191986.html

在平时的开发当中,一个项目往往包含了大量的方法,可能有成千上万个。如何去保证这些方法产生的结果是我们想要的呢?当然了,最容易想到的一个方式,就是我们通过System.out来输出我们的结果,看看是不是满足我们的需求,但是项目中这些成千上万个方法,我们总不能在每一个方法中都去输出一遍嘛。这也太枯燥了。这时候用我们的单元测试框架junit就可以很好地解决这个问题。文章源自玩技e族-https://www.playezu.com/191986.html

junit如何解决这个问题的呢?答案在于内部提供了一个断言机制,他能够将我们预期的结果和实际的结果进行比对,判断出是否满足我们的期望。文章源自玩技e族-https://www.playezu.com/191986.html

预备工作文章源自玩技e族-https://www.playezu.com/191986.html

junit4是一个单元测试框架,既然是框架,这也就意味着jdk并没有为我们提供api,因此在这里我们就需要导入相关的依赖。文章源自玩技e族-https://www.playezu.com/191986.html

一起玩转微服务:单元测试插图
文章源自玩技e族-https://www.playezu.com/191986.html

junit4是一个单元测试框架,既然是框架,这也就意味着jdk并没有为我们提供api,因此在这里我们就需要导入相关的依赖。文章源自玩技e族-https://www.playezu.com/191986.html

这里的版本是4.12。当然还有最新的版本。你可以手动选择。这里选用的是4的版本。文章源自玩技e族-https://www.playezu.com/191986.html

案例文章源自玩技e族-https://www.playezu.com/191986.html

这里我们要测试的功能超级简单,就是加减乘除法的验证。文章源自玩技e族-https://www.playezu.com/191986.html

一起玩转微服务:单元测试插图1

然后我们看看如何使用junit去测试。

一起玩转微服务:单元测试插图2

以上就是我们的单元测试,需要遵循以下规则:

  • 每一个测试方法上使用@Test进行修饰
  • 每一个测试方法必须使用public void 进行修饰
  • 每一个测试方法不能携带参数
  • 测试代码和源代码在两个不同的项目路径下
  • 测试类的包应该和被测试类保持一致
  • 测试单元中的每个方法必须可以独立测试

以上的6条规则,是在使用单元测试的必须项,当然junit也建议我们在每一个测试方法名加上test前缀,表明这是一个测试方法。

assertEquals是一个断言的规则,里面有两个参数,第一个参数表明我们预期的值,第二个参数表示实际运行的值。

我们运行一下测试类,就会运行每一个测试方法,我们也可以运行某一个,只需要在相应的测试方法上面右键运行即可。如果运行成功编辑器的控制台不会出现错误信息,如果有就会出现failure等信息。

运行流程

在上面的每一个测试方法中,代码是相当简单的,就一句话。现在我们分析一下这个测试的流程是什么:

一起玩转微服务:单元测试插图3

在上面的代码中,我们使用了两个测试方法,还有junit运行整个流程方法。我们可以运行一下,就会出现下面的运行结果:

一起玩转微服务:单元测试插图4

从上面的结果我们来画一张流程图就知道了:

一起玩转微服务:单元测试插图5

如果我们使用过SSM等其他的一些框架,经常会在before中添加打开数据库等预处理的代码,也会在after中添加关闭流等相关代码。

注解

对于@Test,里面有很多参数供我们去选择。我们来认识一下

@Test(expected=XX.class) 这个参数表示我们期望会出现什么异常,比如说在除法中,我们1/0会出现ArithmeticException异常,那这里@Test(expected=ArithmeticException.class)。在测试这个除法时候依然能够通过。

@Test(timeout=毫秒 ) 这个参数表示如果测试方法在指定的timeout内没有完成,就会强制停止。

@Ignore 这个注解其实基本上不用,他的意思是所修饰的测试方法会被测试运行器忽略。?@RunWith 更改测试运行器。

测试套件

如果我们的项目中如果有成千上万个方法,那此时也要有成千上万个测试方法嘛?如果这样junit使用起来还不如System.out呢,现在我们认识一下测试嵌套的方法,他的作用是我们把测试类封装起来,也就是把测试类嵌套起来,只需要运行测试套件,就能运行所有的测试类了。

一起玩转微服务:单元测试插图6

下面我们使用测试套件,把这些测试类嵌套在一起。

一起玩转微服务:单元测试插图7

参数化设置

什么是参数化设置呢?在一开始的代码中我们看到,测试加法的时候是1+1,不过我们如果要测试多组数据怎么办?总不能一个一个输入,然后运行测试吧。这时候我们可以把我们需要测试的数据先配置好。

一起玩转微服务:单元测试插图8

这时候再去测试,只需要去选择相应的值即可,避免了我们一个一个手动输入。

spring boot + junit

通过spring suite tools新建工程

一起玩转微服务:单元测试插图9


1. Controller

@RestController
  @RequestMapping
  public class BookController {
  @RequestMapping("/books")
  public String book() {
  System.out.println("controller");
  return "book";
  }
  }

Test1 引入Spring上下文,但不启动tomcat

@RunWith(SpringRunner.class)
  @SpringBootTest //引入Spring上下文 -> 上下文中的 bean 可用,自动注入
  public class BookControllerTest {
  @Autowired
  private BookController bookController; //自动注入
  @Test
  public void testControllerExists() {
  Assert.assertNotNull(bookController);
  }
  }

Test2 引入Spring上下文,且启动Tomcat 模拟生产环境,接收Http请求

package com.cloud.skyme;
  import org.junit.Assert;
  import org.junit.jupiter.api.Test;
  import org.junit.runner.RunWith;
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.boot.test.context.SpringBootTest;
  import org.springframework.boot.test.web.client.TestRestTemplate;
  import org.springframework.boot.web.server.LocalServerPort;
  import org.springframework.test.context.junit4.SpringRunner;
  /**
  * @author zhangfeng
  * web单元测试
  *
  */
  @RunWith(SpringRunner.class)
  @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
  class Chapter0302junitApplicationTests {
  @LocalServerPort
  private int port;
  @Autowired
  private TestRestTemplate restTemplate;
  @Test
  public void testControllerExists() {
  Assert.assertEquals(this.restTemplate.getForObject("http://localhost:" + port + "/books", String.class), "book");
  }
  }

@RunWith(SpringRunner.class),让测试运行于Spring测试环境,此注释在org.springframework.test.annotation包中提供。

@SpringBootTest指定Sspring Bboot程序的测试引导入口。

TestRestTemplate是用于测试rest接口的模板类。

运行单元测试,测试上面边构建的Wweb地址,可以看到输出的测试结果与期望的结果相同.

运行单元测试,得到与期望相同的结果。

13:31:03.722 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
  13:31:03.739 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
  13:31:03.801 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.cloud.skyme.Chapter0302junitApplicationTests] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper]
  13:31:03.830 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.cloud.skyme.Chapter0302junitApplicationTests], using SpringBootContextLoader
  13:31:03.837 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.cloud.skyme.Chapter0302junitApplicationTests]: class path resource [com/cloud/skyme/Chapter0302junitApplicationTests-context.xml] does not exist
  13:31:03.838 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.cloud.skyme.Chapter0302junitApplicationTests]: class path resource [com/cloud/skyme/Chapter0302junitApplicationTestsContext.groovy] does not exist
  13:31:03.838 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [com.cloud.skyme.Chapter0302junitApplicationTests]: no resource found for suffixes {-context.xml, Context.groovy}.
  13:31:03.839 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils - Could not detect default configuration classes for test class [com.cloud.skyme.Chapter0302junitApplicationTests]: Chapter0302junitApplicationTests does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
  13:31:03.918 [main] DEBUG org.springframework.test.context.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [com.cloud.skyme.Chapter0302junitApplicationTests]
  13:31:04.070 [main] DEBUG org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider - Identified candidate component class: file [C:\java\workspace\microservice\chapter0302junit\target\classes\com\cloud\skyme\Chapter0302junitApplication.class]
  13:31:04.073 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Found @SpringBootConfiguration com.cloud.skyme.Chapter0302junitApplication for test class com.cloud.skyme.Chapter0302junitApplicationTests
  13:31:04.225 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - @TestExecutionListeners is not present for class [com.cloud.skyme.Chapter0302junitApplicationTests]: using defaults.
  13:31:04.226 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener, org.springframework.test.context.event.EventPublishingTestExecutionListener]
  13:31:04.243 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Skipping candidate TestExecutionListener [org.springframework.test.context.transaction.TransactionalTestExecutionListener] due to a missing dependency. Specify custom listener classes or make the default listener classes and their required dependencies available. Offending class: [org/springframework/transaction/interceptor/TransactionAttributeSource]
  13:31:04.244 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Skipping candidate TestExecutionListener [org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener] due to a missing dependency. Specify custom listener classes or make the default listener classes and their required dependencies available. Offending class: [org/springframework/transaction/interceptor/TransactionAttribute]
  13:31:04.244 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@7133da86, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@3232a28a, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@73e22a3d, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@47faa49c, org.springframework.test.context.support.DirtiesContextTestExecutionListener@28f2a10f, org.springframework.test.context.event.EventPublishingTestExecutionListener@f736069, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@6da21078, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@7fee8714, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@4229bb3f, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@56cdfb3b, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@2b91004a, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener@20ccf40b]
  13:31:04.250 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - Before test class: context [DefaultTestContext@6cd28fa7 testClass = Chapter0302junitApplicationTests, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@614ca7df testClass = Chapter0302junitApplicationTests, locations = '{}', classes = '{class com.cloud.skyme.Chapter0302junitApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true, server.port=0}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@3b07a0d6, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@14d3bc22, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@45b9a632, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@5e316c74, org.springframework.boot.test.context.SpringBootTestArgs@1], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> false]], class annotated with @DirtiesContext [false] with mode [null].
  13:31:04.267 [main] DEBUG org.springframework.test.context.support.DependencyInjectionTestExecutionListener - Performing dependency injection for test context [[DefaultTestContext@6cd28fa7 testClass = Chapter0302junitApplicationTests, testInstance = com.cloud.skyme.Chapter0302junitApplicationTests@31fa1761, testMethod = [null], testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@614ca7df testClass = Chapter0302junitApplicationTests, locations = '{}', classes = '{class com.cloud.skyme.Chapter0302junitApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true, server.port=0}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@3b07a0d6, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@14d3bc22, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@45b9a632, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@5e316c74, org.springframework.boot.test.context.SpringBootTestArgs@1], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> false]]].
  13:31:04.306 [main] DEBUG org.springframework.test.context.support.TestPropertySourceUtils - Adding inlined properties to environment: {spring.jmx.enabled=false, org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true, server.port=0}
  . ____ _ __ _ _
  /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
  ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
  \\/ ___)| |_)| | | | | || (_| | ) ) ) )
  ' |____| .__|_| |_|_| |_\__, | / / / /
  =========|_|==============|___/=/_/_/_/
  :: Spring Boot :: (v2.3.1.RELEASE)
  2020-06-28 13:31:04.940 INFO 8376 --- [ main] c.c.s.Chapter0302junitApplicationTests : Starting Chapter0302junitApplicationTests on WIN-55FHBQI56BD with PID 8376 (started by Administrator in C:\java\workspace\microservice\chapter0302junit)
  2020-06-28 13:31:04.942 INFO 8376 --- [ main] c.c.s.Chapter0302junitApplicationTests : No active profile set, falling back to default profiles: default
  2020-06-28 13:31:09.134 INFO 8376 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 0 (http)
  2020-06-28 13:31:09.160 INFO 8376 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
  2020-06-28 13:31:09.161 INFO 8376 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.36]
  2020-06-28 13:31:09.372 INFO 8376 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
  2020-06-28 13:31:09.372 INFO 8376 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 4316 ms
  2020-06-28 13:31:10.029 INFO 8376 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
  2020-06-28 13:31:10.655 INFO 8376 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 59724 (http) with context path ''
  2020-06-28 13:31:10.673 INFO 8376 --- [ main] c.c.s.Chapter0302junitApplicationTests : Started Chapter0302junitApplicationTests in 6.362 seconds (JVM running for 8.218)
  2020-06-28 13:31:11.423 INFO 8376 --- [o-auto-1-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
  2020-06-28 13:31:11.423 INFO 8376 --- [o-auto-1-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
  2020-06-28 13:31:11.461 INFO 8376 --- [o-auto-1-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 37 ms
  controller
  2020-06-28 13:31:13.497 INFO 8376 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'

一起玩转微服务:单元测试插图10

这样,一个web应用从构建到单元测试就都已经完成了,可见,构建一个Spring Web MVC的应用就是如此简单。

 
匿名

发表评论

匿名网友
确定

拖动滑块以完成验证