在项目开发中,测试环节是非常重要的,所以选择好的代码测试工具也显得尤为重要。
首先,基于前三篇的代码,先修改一些 Jar 包的版本,都用目前最新版本(强迫症!!!)。
junit 版本修改:3.8.1 -》 4.12
spring boot 版本修改:1.4.2.RELEASE -》 2.0.2.RELEASE
修改后 pom 文件如下:
4.0.0
com.menglanglang
test-springboot
0.0.1-SNAPSHOT
jar
test-springboot
http://blog.csdn.net/tzhuwb
UTF-8
junit
junit
4.12
test
org.springframework.boot
spring-boot-starter-web
2.0.2.RELEASE
org.springframework.boot
spring-boot-devtools
2.0.2.RELEASE
true
org.springframework.boot
spring-boot-maven-plugin
true
spring-snapshots
http://repo.spring.io/snapshot
true
spring-milestones
http://repo.spring.io/milestone
spring-snapshots
http://repo.spring.io/snapshot
spring-milestones
http://repo.spring.io/milestone
一、使用 Junit 测试方法
创建 controller 包,并创建 TestController.java 测试类,代码如下:
package com.menglanglang.test.springboot.controller;
import org.junit.Test;
import org.springframework.web.bind.annotation.RestController;
/**
* @desc Controller测试类
*
* @author 孟郎郎
* @blog http://blog.csdn.net/tzhuwb
* @version 1.0
* @date 2018年5月26日上午8:14:53
*/
@RestController
public class TestController {
@Test
public void test() {
System.out.println("测试方法test()");
}
}
右键 -》Run as -》 JUnit Test。
在控制台查看结果,输出为:
测试方法test()
二、添加 spring-boot-starter-test 依赖包
在 pom 中添加依赖包,代码如下:
org.springframework.boot
spring-boot-starter-test
2.0.2.RELEASE
test
三、修改测试类 TestController.java
修改原测试类,添加 Spring Boot 注解,支持测试。
package com.menglanglang.test.springboot.controller;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.bind.annotation.RestController;
/**
* @desc Controller测试类
*
* @author 孟郎郎
* @blog http://blog.csdn.net/tzhuwb
* @version 1.0
* @date 2018年5月26日上午8:14:53
*/
@RestController
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestController {
@Test
public void test() {
System.out.println("测试方法test()");
}
}
在控制台查看结果,输出为:
10:47:22,789 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback-test.xml]
10:47:22,789 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback.groovy]
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]
10:47:22,842 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - debug attribute not set
10:47:22,842 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.core.ConsoleAppender]
10:47:22,848 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [STDOUT]
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
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]
10:47:22,900 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [baselog]
10:47:22,908 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy@21617358 - No compression will be used
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
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'.
10:47:22,912 |-INFO in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@397ed7 - Roll-over at midnight.
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
10:47:22,916 |-WARN in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@397ed7 - SizeAndTimeBasedFNATP is deprecated. Use SizeAndTimeBasedRollingPolicy instead
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
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
10:47:22,920 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[baselog] - Active log file name: log/base.log
10:47:22,920 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[baselog] - File property is set to [log/base.log]
10:47:22,921 |-INFO in ch.qos.logback.classic.joran.action.RootLoggerAction - Setting level of ROOT logger to INFO
10:47:22,921 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [STDOUT] to Logger[ROOT]
10:47:22,922 |-INFO in ch.qos.logback.classic.joran.action.LoggerAction - Setting level of logger [com.menglanglang.test.springboot] to DEBUG
10:47:22,922 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [baselog] to Logger[com.menglanglang.test.springboot]
10:47:22,922 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - End of configuration.
10:47:22,922 |-INFO in ch.qos.logback.classic.joran.JoranConfigurator@10ab905 - Registering current configuration as safe fallback point
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
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}.
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.
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
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]
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]
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.0.2.RELEASE)
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)
2018-05-26 10:47:23,611 DEBUG (StartupInfoLogger.java:53)- Running with Spring Boot v2.0.2.RELEASE, Spring v5.0.6.RELEASE
2018-05-26 10:47:23,613 INFO (SpringApplication.java:659)- No active profile set, falling back to default profiles: default
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
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]
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
2018-05-26 10:47:24,974 INFO (AbstractHandlerMethodMapping.java:547)- Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
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)
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]
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]
2018-05-26 10:47:25,397 INFO (StartupInfoLogger.java:59)- Started TestController in 2.021 seconds (JVM running for 2.908)
测试方法test()
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