Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement SpringBoot Unit Test

2025-04-08 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article will explain in detail how to implement SpringBoot unit testing for you. The editor thinks it is very practical, so I share it with you for reference. I hope you can get something after reading this article.

Demo (SpringBoot Project)

Classes being tested:

Import org.springframework.stereotype.Service;@Servicepublic class TestService {public String sayHi () {return "hi";} public int divide (int a, int b) {return a / b;}}

Test the code:

Import static org.junit.Assert.*;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.junit4.SpringRunner;@RunWith (SpringRunner.class) @ SpringBootTestpublic class TestServiceTest {@ Autowired TestService testService; @ Testpublic void testSayHi () {TestService testService = new TestService (); String result = testService.sayHi () AssertEquals ("hi", result); @ Test public void testDivide () {TestService testService = new TestService (); int result = testService.divide (3,6); assertTrue (result >-1);}}

Pom.xml profile

! [cobertura] (C:\ Users\ jiaflu\ Desktop\ cobertura.PNG) 4.0.0 org.springframework.boot spring-boot-starter-parent 2.1.5.RELEASE com.jiaflu learn_springoot 0.0.1-SNAPSHOT learn_springoot Demo project for Spring Boot 1.8 2.9.8 org.springframework .boot spring-boot-starter org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-maven -plugin org.apache.maven.plugins maven-compiler-plugin 1.8 1.8 org.apache.maven.plugins maven-surefire-plugin 2.5 org.codehaus.mojo cobertura-maven-plugin 2.5.2 UTF-8 html xml

Run mvn cobertura:cobertura to view the screenshot:

Coverage test report generation (cobertura) cobertura principle

The execution process of cobertura is roughly as follows:

Use instrument to modify our compiled class file, located in target\ generated-classes.

The test is executed and the test data is output to xxx.ser, located at target\ cobertura\ cobertura.ser.

Use report to generate coverage reports.

1.instrument

Instrument:cobertura uses instrument to modify our compiled class file and add the statistical code of cobertura to the code. And generate a .ser file (for the output of coverage data).

During execution using instrument, CoberturaInstrumenter first calls the analysis listener to analyze the given compiled .class to get the touchPoint (which can be considered to correspond to the lines to be overwritten in the source code) and other information needed. The injection listener is then called to inject the information into the new .class and save it to the\ target\ generated-classes directory.

Example:

/ Source code recreated from a .class file by IntelliJ IDEA// (powered by Fernflower decompiler) / / package com.cisco.webex.cmse.soa.soaservice.service;import net.sourceforge.cobertura.coveragedata.HasBeenInstrumented;import net.sourceforge.cobertura.coveragedata.TouchCollector;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.PropertySource;import org.springframework.stereotype.Service @ PropertySource ({"classpath:application.properties"}) @ Servicepublic class PropertyService implements HasBeenInstrumented {private static final Logger logger; @ Value ("${cdp.instance.url}") private String cdpInstanUrl; @ Value ("${soa.instance.url}") private String soaInstanceUrl; @ Value ("${github.api.token}") public String gitApiToken; @ Value ("${github.instance.url}") private String githubInstance @ Value ("${github.repo.template.owner}") private String tplRepoOwner; @ Value ("${github.repo.consul.owner}") private String consulRepoOwner; @ Value ("${slm.listen.queue.name}") private String slmListenQueue; public PropertyService () {boolean var1 = false; int _ _ cobertura__branch__number__ = true TouchCollector.touch ("com.cisco.webex.cmse.soa.soaservice.service.PropertyService", 12); super ();} public String getCdpInstanUrl () {boolean var1 = false; int _ cobertura__branch__number__ = true; TouchCollector.touch ("com.cisco.webex.cmse.soa.soaservice.service.PropertyService", 33); return this.cdpInstanUrl;}. Public void setSlmListenQueue (String () V) {boolean var2 = false; int _ _ cobertura__branch__number__ = true; TouchCollector.touch ("com.cisco.webex.cmse.soa.soaservice.service.PropertyService", 85); this.slmListenQueue = slmListenQueue; TouchCollector.touch ("com.cisco.webex.cmse.soa.soaservice.service.PropertyService", 86);} static {boolean var0 = false; boolean var1 = true TouchCollector.touch ("com.cisco.webex.cmse.soa.soaservice.service.PropertyService", 13); logger = LoggerFactory.getLogger (PropertyService.class);}} 2. Perform a test

When the test case is executed, the .class modified by cobertura is referenced, and the test information is written to the cobertura.ser archive.

3. Generate a report

Get the coverage data from cobertura.ser, and then combine the source code provided in src to generate the final coverage report, which is placed under the target\ site\ cobertura path. If you have configured to generate a report in html format, you can view the coverage test report through index.html.

SpringBoot pom.xml configuration

Add the following dependencies:

Org.springframework.boot spring-boot-maven-plugin org.apache.maven.plugins maven-compiler-plugin 1.8 1.8 org.apache. Maven.plugins maven-surefire-plugin 2.5-noverify org.codehaus.mojo cobertura-maven-plugin 2.5.2 Xml html

Mining pit:

The following problems occurred when using the mvn cobertura:cobertura command to generate the test coverage report (intercept part, the error was reported for the following reasons):

Reason:

Expected stackmap frame at this location.

Bytecode:

0x0000000: 2ab4 001b 2bb9 002e 0200 c600 2f2a b400

0x0000010: 1b2b b900 2e02 00c0 0030 b600 34c6 001c

Solution:

I use jdk1.8. Add the jvm parameter-noverify. You can add the configuration in the pom file. For configuration, please see pom.xml above.

Check the information online and add the jvm parameter-XX:-UseSplitVerifier to jdk1.7 (1.8no-XX:-UseSplitVerifier parameter)

Command introduction

Cobertura:check

Verify the coverage of the test case according to the latest source code markup (generated class file). If it does not meet the requirements, the execution fails.

Cobertura:check-integration-test

This command is the same as the cobertura:check function, except that the maven lifecycle of the binding is different. Cobertura: check binds test, cobertura:check-integration-test binds verify. To be clear, there is a test run unit test and an integration-test run integration test in the maven life cycle. And before verify is integration-test. That is, cobertura:check-integration-test covers more test cases than cobertura:check.

Cobertura:clean

This is easy to understand, which is to clean up the files in the directory / target/cobertura/. It is found that there is only one file cobertura.ser.

Cobertura:cobertura

The key command of this plug-in. Mark compiled files, run unit tests, and generate test reports.

Cobertura:cobertura-integration-test

It does the same thing as cobertura:cobertura, except that it includes integration test cases.

Cobertura:dump-datafile

Output coverage data on the command line. The data is based on the generated class file. I don't understand what he means by this order. In a later interesting experiment, we will use this command to better understand cobertura-maven-plugin.

Cobertura:help

Cobertura:instrument

Mark the compiled class file. Executing this command will generate a set of class files in the directory / target/generated-classes/cobertura.

Instructions for using maven-surefire-plugin

Maven itself is not a unit testing framework, it just executes JUnit or TestNG test cases through plug-ins when the build is executed to a specific lifecycle phase. This plug-in is maven-surefire-plugin, also known as Test Runner (Test Runner), which is compatible with JUnit 3, JUnit 4, and TestNG.

By default, the test target of maven-surefire-plugin automatically executes all test classes that conform to a set of naming patterns under the test source code path (default is src/test/java/). This set of patterns are:

* / Test.java: all Java classes named Test switches in any subdirectory.

* / Test.java: all Java classes that are named ending in Test in any subdirectory.

* / TestCase.java: all Java classes that are named ending in TestCase in any subdirectory.

Maven-surefire-plugin plug-in application:

1. Skip the test

Skip the test run mvn package-DskipTests

Or provide this property through pom:

Org.apache.maven.plugins maven-surefire-plugin 2.5 true

Skip compiling mvn package-Dmaven.test.skip=true of test code

Or provide this property through pom:

Org.apache.maven.plugin maven-compiler-plugin 2.1 true 2. Dynamically specify test cases to run mvn test-Dtest=RandomGeneratorTest

You can also use wildcards:

Mvn test-Dtest=Random*Test

Or you can use the "," sign to specify multiple test classes:

Mvn test-Dtest=Random*Test,AccountCaptchaServiceTest

If no test class is specified, an error will be reported and the build will fail:

Mvn test-Dtest

At this point, you can add the-DfailIfNoTests=false parameter to tell maven-surefire-plugin not to report an error even if there are no tests:

Mvn test-Dtest-DfailIfNoTests=false3. Include and exclude test cases org.apache.maven.plugins maven-surefire-plugin 2.5 * * / * Tests.java * * / * ServiceTest.java * * / TempDaoTest.java on "how to implement SpringBoot unit tests" is shared here Hope that the above content can be helpful to you, so that you can learn more knowledge, if you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report