Spring Boot 初级入门教程(四) —— 代码测试配置(附源码)
2018年05月26日 10:49:49 SpringBoot ⁄ 共 13912字 暂无评论 ⁄ 被围观 823次

在项目开发中,测试环节是非常重要的,所以选择好的代码测试工具也显得尤为重要。

首先,基于前三篇的代码,先修改一些 Jar 包的版本,都用目前最新版本(强迫症!!!)。

junit 版本修改:3.8.1 -》 4.12

spring boot 版本修改:1.4.2.RELEASE -》 2.0.2.RELEASE

修改后 pom 文件如下:

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  2.     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
  3.     <modelVersion>4.0.0</modelVersion>  
  4.   
  5.     <groupId>com.menglanglang</groupId>  
  6.     <artifactId>test-springboot</artifactId>  
  7.     <version>0.0.1-SNAPSHOT</version>  
  8.     <packaging>jar</packaging>  
  9.   
  10.     <name>test-springboot</name>  
  11.     <url>http://blog.csdn.net/tzhuwb</url>  
  12.   
  13.     <properties>  
  14.         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  
  15.     </properties>  
  16.   
  17.     <dependencies>  
  18.         <dependency>  
  19.             <groupId>junit</groupId>  
  20.             <artifactId>junit</artifactId>  
  21.             <version>4.12</version>  
  22.             <scope>test</scope>  
  23.         </dependency>  
  24.   
  25.         <!-- 该依赖包提供了MVC、AOP等的依赖包 -->  
  26.         <dependency>  
  27.             <groupId>org.springframework.boot</groupId>  
  28.             <artifactId>spring-boot-starter-web</artifactId>  
  29.             <version>2.0.2.RELEASE</version>  
  30.         </dependency>  
  31.   
  32.         <!-- 添加Spring Boot Devtools依赖包 -->  
  33.         <dependency>  
  34.             <groupId>org.springframework.boot</groupId>  
  35.             <artifactId>spring-boot-devtools</artifactId>  
  36.             <version>2.0.2.RELEASE</version>  
  37.             <optional>true</optional>  
  38.         </dependency>  
  39.     </dependencies>  
  40.   
  41.     <build>  
  42.         <plugins>  
  43.             <!-- 这是Spring Boot Devtools Plugin的配置 -->  
  44.             <plugin>  
  45.                 <groupId>org.springframework.boot</groupId>  
  46.                 <artifactId>spring-boot-maven-plugin</artifactId>  
  47.                 <configuration>  
  48.                     <!-- 如果没有fork配置,可能devtools不会起作用,即不会restart -->  
  49.                     <fork>true</fork>  
  50.                 </configuration>  
  51.             </plugin>  
  52.         </plugins>  
  53.     </build>  
  54.   
  55.     <!-- Add Spring repositories -->  
  56.     <!-- (you don't need this if you are using a .RELEASE version) -->  
  57.     <repositories>  
  58.         <repository>  
  59.             <id>spring-snapshots</id>  
  60.             <url>http://repo.spring.io/snapshot</url>  
  61.             <snapshots>  
  62.                 <enabled>true</enabled>  
  63.             </snapshots>  
  64.         </repository>  
  65.         <repository>  
  66.             <id>spring-milestones</id>  
  67.             <url>http://repo.spring.io/milestone</url>  
  68.         </repository>  
  69.     </repositories>  
  70.     <pluginRepositories>  
  71.         <pluginRepository>  
  72.             <id>spring-snapshots</id>  
  73.             <url>http://repo.spring.io/snapshot</url>  
  74.         </pluginRepository>  
  75.         <pluginRepository>  
  76.             <id>spring-milestones</id>  
  77.             <url>http://repo.spring.io/milestone</url>  
  78.         </pluginRepository>  
  79.     </pluginRepositories>  
  80. </project>  

一、使用 Junit 测试方法

创建 controller 包,并创建 TestController.java 测试类,代码如下:

  1. package com.menglanglang.test.springboot.controller;  
  2.   
  3. import org.junit.Test;  
  4. import org.springframework.web.bind.annotation.RestController;  
  5.   
  6. /** 
  7.  * @desc Controller测试类 
  8.  * 
  9.  * @author 孟郎郎 
  10.  * @blog http://blog.csdn.net/tzhuwb 
  11.  * @version 1.0 
  12.  * @date 2018年5月26日上午8:14:53 
  13.  */  
  14. @RestController  
  15. public class TestController {  
  16.   
  17.     @Test  
  18.     public void test() {  
  19.         System.out.println("测试方法test()");  
  20.     }  
  21.   
  22. }  

右键 -》Run as -》 JUnit Test。

在控制台查看结果,输出为:

测试方法test()

二、添加 spring-boot-starter-test 依赖包

在 pom 中添加依赖包,代码如下:

		<!-- 添加 Spring Boot 测试依赖包 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<version>2.0.2.RELEASE</version>
			<scope>test</scope>
		</dependency>

三、修改测试类 TestController.java

修改原测试类,添加 Spring Boot 注解,支持测试。

  1. package com.menglanglang.test.springboot.controller;  
  2.   
  3. import org.junit.Test;  
  4. import org.junit.runner.RunWith;  
  5. import org.springframework.boot.test.context.SpringBootTest;  
  6. import org.springframework.test.context.junit4.SpringRunner;  
  7. import org.springframework.web.bind.annotation.RestController;  
  8.   
  9. /** 
  10.  * @desc Controller测试类 
  11.  * 
  12.  * @author 孟郎郎 
  13.  * @blog http://blog.csdn.net/tzhuwb 
  14.  * @version 1.0 
  15.  * @date 2018年5月26日上午8:14:53 
  16.  */  
  17. @RestController  
  18. @RunWith(SpringRunner.class)  
  19. @SpringBootTest  
  20. public class TestController {  
  21.   
  22.     @Test  
  23.     public void test() {  
  24.         System.out.println("测试方法test()");  
  25.     }  
  26.   
  27. }  

在控制台查看结果,输出为:

  1. 10:47:22,789 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback-test.xml]  
  2. 10:47:22,789 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback.groovy]  
  3. 10:47:22,789 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Found resource [logback.xml] at [file:/D:/workspace/workspace-sts-3.9.4.RELEASE-x86/test-springboot/target/classes/logback.xml]  
  4. 10:47:22,842 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - debug attribute not set  
  5. 10:47:22,842 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.core.ConsoleAppender]  
  6. 10:47:22,848 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [STDOUT]  
  7. 10:47:22,854 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default type [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property  
  8. 10:47:22,897 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.core.rolling.RollingFileAppender]  
  9. 10:47:22,900 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [baselog]  
  10. 10:47:22,908 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy@21617358 - No compression will be used  
  11. 10:47:22,909 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy@21617358 - Will use the pattern log/base.log.%d.%i for the active file  
  12. 10:47:22,911 |-INFO in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@397ed7 - The date pattern is 'yyyy-MM-dd' from file name pattern 'log/base.log.%d.%i'.  
  13. 10:47:22,912 |-INFO in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@397ed7 - Roll-over at midnight.  
  14. 10:47:22,916 |-INFO in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@397ed7 - Setting initial period to Sat May 26 10:47:06 CST 2018  
  15. 10:47:22,916 |-WARN in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@397ed7 - SizeAndTimeBasedFNATP is deprecated. Use SizeAndTimeBasedRollingPolicy instead  
  16. 10:47:22,916 |-WARN in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@397ed7 - For more information see http://logback.qos.ch/manual/appenders.html#SizeAndTimeBasedRollingPolicy  
  17. 10:47:22,918 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default type [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property  
  18. 10:47:22,920 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[baselog] - Active log file name: log/base.log  
  19. 10:47:22,920 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[baselog] - File property is set to [log/base.log]  
  20. 10:47:22,921 |-INFO in ch.qos.logback.classic.joran.action.RootLoggerAction - Setting level of ROOT logger to INFO  
  21. 10:47:22,921 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [STDOUT] to Logger[ROOT]  
  22. 10:47:22,922 |-INFO in ch.qos.logback.classic.joran.action.LoggerAction - Setting level of logger [com.menglanglang.test.springboot] to DEBUG  
  23. 10:47:22,922 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [baselog] to Logger[com.menglanglang.test.springboot]  
  24. 10:47:22,922 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - End of configuration.  
  25. 10:47:22,922 |-INFO in ch.qos.logback.classic.joran.JoranConfigurator@10ab905 - Registering current configuration as safe fallback point  
  26.   
  27. 2018-05-26 10:47:23,057 INFO (AbstractTestContextBootstrapper.java:308)- Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.menglanglang.test.springboot.controller.TestController], using SpringBootContextLoader  
  28. 2018-05-26 10:47:23,063 INFO (AbstractContextLoader.java:264)- Could not detect default resource locations for test class [com.menglanglang.test.springboot.controller.TestController]: no resource found for suffixes {-context.xml, Context.groovy}.  
  29. 2018-05-26 10:47:23,064 INFO (AnnotationConfigContextLoaderUtils.java:83)- Could not detect default configuration classes for test class [com.menglanglang.test.springboot.controller.TestController]: TestController does not declare any static, non-private, non-final, nested classes annotated with @Configuration.  
  30. 2018-05-26 10:47:23,186 INFO (SpringBootTestContextBootstrapper.java:244)- Found @SpringBootConfiguration com.menglanglang.test.springboot.App for test class com.menglanglang.test.springboot.controller.TestController  
  31. 2018-05-26 10:47:23,311 INFO (AbstractTestContextBootstrapper.java:248)- 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.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]  
  32. 2018-05-26 10:47:23,325 INFO (AbstractTestContextBootstrapper.java:177)- Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@1f9b85e, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@4e1977, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@d68fcd, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@17e949d, org.springframework.test.context.support.DirtiesContextTestExecutionListener@1b9f5a4, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@18edcc5, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@102881e, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@bd319f, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@be339, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@1ca7889]  
  33.   
  34.   .   ____          _            __ _ _  
  35.  /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \  
  36. ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \  
  37.  \\/  ___)| |_)| | | | | || (_| |  ) ) ) )  
  38.   '  |____| .__|_| |_|_| |_\__, | / / / /  
  39.  =========|_|==============|___/=/_/_/_/  
  40.  :: Spring Boot ::        (v2.0.2.RELEASE)  
  41.   
  42. 2018-05-26 10:47:23,610 INFO (StartupInfoLogger.java:50)- Starting TestController on LangLang-PC with PID 7800 (started by LangLang in D:\workspace\workspace-sts-3.9.4.RELEASE-x86\test-springboot)  
  43. 2018-05-26 10:47:23,611 DEBUG (StartupInfoLogger.java:53)- Running with Spring Boot v2.0.2.RELEASE, Spring v5.0.6.RELEASE  
  44. 2018-05-26 10:47:23,613 INFO (SpringApplication.java:659)- No active profile set, falling back to default profiles: default  
  45. 2018-05-26 10:47:23,649 INFO (AbstractApplicationContext.java:590)- Refreshing org.springframework.web.context.support.GenericWebApplicationContext@519cb4: startup date [Sat May 26 10:47:23 CST 2018]; root of context hierarchy  
  46. 2018-05-26 10:47:24,671 INFO (AbstractUrlHandlerMapping.java:373)- Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]  
  47. 2018-05-26 10:47:24,873 INFO (RequestMappingHandlerAdapter.java:574)- Looking for @ControllerAdvice: org.springframework.web.context.support.GenericWebApplicationContext@519cb4: startup date [Sat May 26 10:47:23 CST 2018]; root of context hierarchy  
  48. 2018-05-26 10:47:24,974 INFO (AbstractHandlerMethodMapping.java:547)- Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)  
  49. 2018-05-26 10:47:24,977 INFO (AbstractHandlerMethodMapping.java:547)- Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)  
  50. 2018-05-26 10:47:25,000 INFO (AbstractUrlHandlerMapping.java:373)- Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]  
  51. 2018-05-26 10:47:25,000 INFO (AbstractUrlHandlerMapping.java:373)- Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]  
  52. 2018-05-26 10:47:25,397 INFO (StartupInfoLogger.java:59)- Started TestController in 2.021 seconds (JVM running for 2.908)  
  53. 测试方法test()  
  54. 2018-05-26 10:47:25,492 INFO (AbstractApplicationContext.java:993)- Closing org.springframework.web.context.support.GenericWebApplicationContext@519cb4: startup date [Sat May 26 10:47:23 CST 2018]; root of context hierarchy  

到此,Spring Boot 测试支持添加完毕。

源码下载:https://pan.baidu.com/s/1uOjOHeuPWG3my9VaHVI8Wg

给我留言

留言无头像?