TestNG测试框架的测试方式在IDE中运行很便利,但这种方式无法解决依赖项和版本冲突的问题,Maven解决了各种依赖问题,但无法解决测试用例的忽略、依赖等执行方式,然而将Maven和TestNG深度绑定后就都可兼顾
在Maven项目的配置文件pom.xml
中有个
插件配置项,默认情况下该插件会自动扫描源码路径,也就是src/test/java
下所有符合命名规则的测试用例,也就是
- 以Test开头的测试用例
- 以Test结尾的测试用例
- 以TestCase结尾的测试用例
利用该插件件可以使得Maven与TestNG绑定执行,因此可以使用TestNG的特性,例如忽略某些用例,例如跳过用例,执行顺序等等
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-surefire-pluginartifactId>
<version>2.22.1version>
<configuration>
<argLine>-Dfile.encoding=UTF-8argLine>
<argLine>-Xms1024m -Xxm1024 -XX:PermSize=128m -XX:MaxPermSize=128margLine>
<forkMode>neverforkMode>
<suiteXmlFiles>
<suiteXmlFile>testng.xmlsuiteXmlFile>
suiteXmlFiles>
<reportsDirectory>./result/test-reportreportsDirectory>
configuration>
plugin>
D:\SpringBootDemo>mvn test
[INFO] Scanning for projects...
[INFO]
[INFO] --------------------< com.davieyang:SpringBootDemo >--------------------
[INFO] Building SpringBootDemo 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:3.0.2:resources (default-resources) @ SpringBootDemo ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 1 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.8.0:compile (default-compile) @ SpringBootDemo ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 4 source files to D:\SpringBootDemo\target\classes
[INFO]
[INFO] --- maven-resources-plugin:3.0.2:testResources (default-testResources) @ SpringBootDemo ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory D:\SpringBootDemo\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.0:testCompile (default-testCompile) @ SpringBootDemo ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 2 source files to D:\SpringBootDemo\target\test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.22.1:test (default-test) @ SpringBootDemo ---
[INFO] Surefire report directory: D:\SpringBootDemo\result\test-report
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running TestSuite
01:14:31.302 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCache
AwareContextLoaderDelegate]
01:14:31.329 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBoot
strapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
01:14:31.435 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.davieyang.springboot.controller.CalculatorForPpiCon
trollerTest] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper]
01:14:31.469 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.davieyan
g.springboot.controller.CalculatorForPpiControllerTest], using SpringBootContextLoader
01:14:31.478 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.davieyang.springboot.controller.C
alculatorForPpiControllerTest]: class path resource [com/davieyang/springboot/controller/CalculatorForPpiControllerTest-context.xml] does not exist
01:14:31.497 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.davieyang.springboot.controller.C
alculatorForPpiControllerTest]: class path resource [com/davieyang/springboot/controller/CalculatorForPpiControllerTestContext.groovy] does not exist
01:14:31.499 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [com.davieyang.springboot.controller
.CalculatorForPpiControllerTest]: no resource found for suffixes {-context.xml, Context.groovy}.
01:14:31.635 [main] DEBUG org.springframework.test.context.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.con
text.ActiveProfiles] and class [com.davieyang.springboot.controller.CalculatorForPpiControllerTest]
01:14:31.990 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecuti
onListener@4fdca00a, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@513b52af, org.springframework.test.context.support.DependencyInjectionTestEx
ecutionListener@5a8c93, org.springframework.test.context.support.DirtiesContextTestExecutionListener@3bed3315, org.springframework.test.context.event.EventPublishingTestExecutionListene
r@119b0892]
01:14:32.033 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCache
AwareContextLoaderDelegate]
01:14:32.035 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBoot
strapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
01:14:32.038 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.davieyang.springboot.service.CalculatorForPpiServic
eTest] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper]
01:14:32.042 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.davieyan
g.springboot.service.CalculatorForPpiServiceTest], using SpringBootContextLoader
01:14:32.062 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.davieyang.springboot.service.Calc
ulatorForPpiServiceTest]: class path resource [com/davieyang/springboot/service/CalculatorForPpiServiceTest-context.xml] does not exist
01:14:32.064 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.davieyang.springboot.service.Calc
ulatorForPpiServiceTest]: class path resource [com/davieyang/springboot/service/CalculatorForPpiServiceTestContext.groovy] does not exist
01:14:32.065 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [com.davieyang.springboot.service.Ca
lculatorForPpiServiceTest]: no resource found for suffixes {-context.xml, Context.groovy}.
01:14:32.071 [main] DEBUG org.springframework.test.context.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.con
text.ActiveProfiles] and class [com.davieyang.springboot.service.CalculatorForPpiServiceTest]
01:14:32.077 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecuti
onListener@3902bd2c, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@7d32e714, org.springframework.test.context.support.DependencyInjectionTestEx
ecutionListener@eb6ec6, org.springframework.test.context.support.DirtiesContextTestExecutionListener@34d45ec0, org.springframework.test.context.event.EventPublishingTestExecutionListene
r@18137eab]
01:14:32.161 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - Before test class: context [DefaultTestContext@29ebbdf4 testClass = Calc
ulatorForPpiControllerTest, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@2fd954f testClass = Calculato
rForPpiControllerTest, locations = '{}', classes = '{class com.davieyang.springboot.Application, class com.davieyang.springboot.Application}', contextInitializerClasses = '[]', activePr
ofiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.
springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@7c847072, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectConte
xtCustomizer@2264ea32, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@352ed70d, org.sp
ringframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer
@4e49ce2b, org.springframework.boot.test.context.SpringBootTestArgs@1], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoa
der', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> true]], class annotated with @DirtiesContext [false] wit
h mode [null].
01:14:32.243 [main] DEBUG org.springframework.test.context.support.TestPropertySourceUtils - Adding inlined properties to environment: {spring.jmx.enabled=false, org.springframework.boo
t.test.context.SpringBootTestContextBootstrapper=true}
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.3.3.RELEASE)
2020-08-20 01:14:33.243 INFO 5592 --- [ main] c.d.s.c.CalculatorForPpiControllerTest : Starting CalculatorForPpiControllerTest on DESKTOP-ASA24DF with PID 5592 (D:\SpringBo
otDemo\target\test-classes started by davieyang in D:\SpringBootDemo)
2020-08-20 01:14:33.247 INFO 5592 --- [ main] c.d.s.c.CalculatorForPpiControllerTest : No active profile set, falling back to default profiles: default
2020-08-20 01:14:37.255 INFO 5592 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-08-20 01:14:38.493 INFO 5592 --- [ main] c.d.s.c.CalculatorForPpiControllerTest : Started CalculatorForPpiControllerTest in 6.228 seconds (JVM running for 40.102)
2020-08-20 01:14:38.724 INFO 5592 --- [ main] o.s.mock.web.MockServletContext : Initializing Spring TestDispatcherServlet ''
2020-08-20 01:14:38.793 INFO 5592 --- [ main] o.s.t.web.servlet.TestDispatcherServlet : Initializing Servlet ''
2020-08-20 01:14:38.814 INFO 5592 --- [ main] o.s.t.web.servlet.TestDispatcherServlet : Completed initialization in 0 ms
PASSED: testCase1
PASSED: testCase2
PASSED: testCase3
PASSED: testCase4
PASSED: testCase5
PASSED: testCase6
PASSED: testCase7
PASSED: testCase1
PASSED: testCase2
PASSED: testCase3
PASSED: testCase4
PASSED: testCase5
PASSED: testCase6
PASSED: testCase7
===============================================
D:/SpringBootDemo
Tests run: 14, Failures: 0, Skips: 0
===============================================
Tests run: 14, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 9.783 sec
Results :
Tests run: 14, Failures: 0, Errors: 0, Skipped: 0
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 38.862 s
[INFO] Finished at: 2020-08-20T01:14:40+08:00
[INFO] ------------------------------------------------------------------------
2020-08-20 01:14:40.704 INFO 5592 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
这配置的maven-surefire-plugin
的版本是2.4如果是其他的版本可能配置项需要更改,因为有些配置已经被摒弃了,详细版本差异可查看插件官方地址
在插件的配置项中配置了测试报告生成的路径
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-surefire-pluginartifactId>
<version>2.4version>
<configuration>
<argLine>-Dfile.encoding=UTF-8argLine>
<argLine>-Xms1024m -Xxm1024 -XX:PermSize=128m -XX:MaxPermSize=128margLine>
<properties>
<property>
<name>usedefaultlistenersname>
<value>falsevalue>
property>
<property>
<name>listenername>
<value>org.uncommons.reportng.HTMLReporter, org.uncommons.reportng.JUnitXMLReportervalue>
property>
properties>
<forkMode>neverforkMode>
<suiteXmlFiles>
<suiteXmlFile>testng.xmlsuiteXmlFile>
suiteXmlFiles>
<reportsDirectory>./result/test-reportreportsDirectory>
configuration>
plugin>
如此便可以使用reportng来生成报告,但不能直接执行,需要在pom添加两个依赖
<dependency>
<groupId>org.uncommonsgroupId>
<artifactId>reportngartifactId>
<version>1.1.4version>
<scope>testscope>
dependency>
<dependency>
<groupId>com.google.injectgroupId>
<artifactId>guiceartifactId>
<version>3.0version>
<scope>testscope>
dependency>
第一个是reportng,第二个是生成报告需要的jar包,如果没有添加第二个依赖,会报如下错误并且测试无法执行
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.4:test (default-test) on project SpringBootDemo: com/google/inject/Injector; nested exception is java.lan
g.NoClassDefFoundError: com/google/inject/Injector: com.google.inject.Injector -> [Help 1]