单元测试系列[v1.0.0][Maven深度绑定TestNG]

TestNG测试框架的测试方式在IDE中运行很便利,但这种方式无法解决依赖项和版本冲突的问题,Maven解决了各种依赖问题,但无法解决测试用例的忽略、依赖等执行方式,然而将Maven和TestNG深度绑定后就都可兼顾

在Maven项目的配置文件pom.xml中有个<plugin>maven-surefire-plugin</plugin>插件配置项,默认情况下该插件会自动扫描源码路径,也就是src/test/java下所有符合命名规则的测试用例,也就是

  • 以Test开头的测试用例
  • 以Test结尾的测试用例
  • 以TestCase结尾的测试用例

利用该插件件可以使得Maven与TestNG绑定执行,因此可以使用TestNG的特性,例如忽略某些用例,例如跳过用例,执行顺序等等

配置maven-surefire-plugin

  <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
          <configuration>
            <!--解决用Maven执行测试时日志乱码问题-->
            <argLine>-Dfile.encoding=UTF-8</argLine>
            <!--解决Maven内存溢出问题-->
            <argLine>-Xms1024m -Xxm1024 -XX:PermSize=128m -XX:MaxPermSize=128m</argLine>
            <forkMode>never</forkMode>
            <suiteXmlFiles>
              <suiteXmlFile>testng.xml</suiteXmlFile>
            </suiteXmlFiles>
            <!--定义Maven运行测试生成的报告路径-->
            <reportsDirectory>./result/test-report</reportsDirectory>
          </configuration>
        </plugin>

mvn执行测试

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:用来配置插件,在pom.xml中应该能看到很多插件
  • configuration:用来扩展配置项
  • argLine:用来配置JVM参数和语言格式
  • forkMode:指明要为每个测试创建一个进程,还是所有测试在同一个进程中完成。
    • 默认值为once表示在一个进程中完成所有测试
    • 在surefire2.6版本以上支持always,表示在一个进程中并行运行脚本
    • pretest表示为每一个测试创建新的JVM进程彻底的独立测试,但也是最慢的
    • never表示不创建进程
  • suiteXmlFiles:执行testng.xml配置文件的文件名

测试报告

在插件的配置项中配置了测试报告生成的路径<reportsDirectory>./result/test-report</reportsDirectory>
在这里插入图片描述

在插件中配置监听

<plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.4</version>
          <configuration>
            <!--解决用Maven执行测试时日志乱码问题-->
            <argLine>-Dfile.encoding=UTF-8</argLine>
            <!--解决Maven内存溢出问题-->
            <argLine>-Xms1024m -Xxm1024 -XX:PermSize=128m -XX:MaxPermSize=128m</argLine>
            <properties>
              <property>
                <name>usedefaultlisteners</name>
                <value>false</value>
              </property>
              <property>
                <!--使用reportng的 listener 生成测试报告-->
                <name>listener</name>
                <value>org.uncommons.reportng.HTMLReporter, org.uncommons.reportng.JUnitXMLReporter</value>
              </property>
            </properties>
            <forkMode>never</forkMode>
            <suiteXmlFiles>
              <suiteXmlFile>testng.xml</suiteXmlFile>
            </suiteXmlFiles>
            <!--定义Maven运行测试生成的报告路径-->
            <reportsDirectory>./result/test-report</reportsDirectory>
          </configuration>
        </plugin>

如此便可以使用reportng来生成报告,但不能直接执行,需要在pom添加两个依赖

   <dependency>
      <groupId>org.uncommons</groupId>
      <artifactId>reportng</artifactId>
      <version>1.1.4</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.google.inject</groupId>
      <artifactId>guice</artifactId>
      <version>3.0</version>
      <scope>test</scope>
    </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]

执行测试

配置好后再次使用命令mvn test执行测试生成测试报告如下
在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Davieyang.D.Y

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值