单元测试系列[v1.0.0][SpringBootTest]

创建SpringBoot项目

单元测试系列[v1.0.0][SpringBootTest]_第1张图片

配置pom



<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0modelVersion>

  <groupId>com.davieyanggroupId>
  <artifactId>SpringBootDemoartifactId>
  <version>1.0-SNAPSHOTversion>

  <name>SpringBootDemoname>
  
  <url>http://www.example.comurl>

  <properties>
    <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    <maven.compiler.source>1.7maven.compiler.source>
    <maven.compiler.target>1.7maven.compiler.target>
  properties>

  <dependencies>
    
    <dependency>
      <groupId>org.springframework.bootgroupId>
      <artifactId>spring-boot-starter-testartifactId>
      <version>2.3.3.RELEASEversion>
      <scope>testscope>
    dependency>
    
    <dependency>
      <groupId>org.springframework.bootgroupId>
      <artifactId>spring-boot-starter-webartifactId>
      <version>2.3.3.RELEASEversion>
    dependency>
    
    <dependency>
      <groupId>org.springframework.bootgroupId>
      <artifactId>spring-boot-starter-thymeleafartifactId>
      <version>2.3.3.RELEASEversion>
    dependency>
    
    <dependency>
      <groupId>org.springframework.bootgroupId>
      <artifactId>spring-boot-starter-parentartifactId>
      <version>2.3.3.RELEASEversion>
      <type>pomtype>
    dependency>
    
    <dependency>
      <groupId>org.testnggroupId>
      <artifactId>testngartifactId>
      <version>6.14.3version>
      <scope>testscope>
    dependency>
  dependencies>

.....省略<build>build>......
project>

业务逻辑层实现[Service层]

package com.davieyang.springboot.service;
import org.springframework.stereotype.Service;


@Service
// @Service是Spring框架的业务逻辑层注解
public class CalculatorForPpiService {
    public long calculate(int width, int height, double size){
        long result;
        if (width > 0 && height > 0 && size >0){
            result = Math.round(Math.pow((Math.pow(width, 2) + Math.pow(height, 2)) / Math.pow(size, 2), 0.5));
        }else {
            result = -1;
        }
        return result;
    }
}

控制器层实现[Controller层]

package com.davieyang.springboot.controller;
import javax.annotation.Resource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.davieyang.springboot.service.CalculatorForPpiService;

@RestController
public class CalculatorForPpiController {
    @Resource
    //@Resource是一种注入注解,讲一个Bean注入当前类中,即可使用该Bean
    private CalculatorForPpiService calculatorForPpiService;
    @RequestMapping("/calculate")
    public String calculate(@RequestParam("width") int width, @RequestParam("height") int height, @RequestParam("size") double size){
        //@RequestParam注解用于接收请求参数
        long result=calculatorForPpiService.calculate(width, height, size);
        return "{\"PPI\":" + result + "}";
        //返回JSON格式的字符串
    }
}

package com.davieyang.springboot.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
//@Controller 是Spring框架的控制器层注解,常用的Spring框架的控制器层注解还有@RestController
//@RequestMapping 表示接收用户请求,当用户请求/index时,使用index方法处理,index方法返回的“index-page”代表名为“index-page”的页面
public class IndexController {
    @RequestMapping("/index")
    public String index(){
        return "index-page";
    }
}

表现层实现[View层]


<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js">script>
    <meta charset="UTF-8">
    <title>CalculatorForPpititle>
head>
<body>
    <form>
        <input type="text" id="width" placeholder="屏幕宽(像素)"><br>
        <input type="text" id="height" placeholder="屏幕高(像素)"><br>
        <input type="text" id="size" placeholder="屏幕尺寸(英寸)"><br>
        <button type="button" id="submit">计算button>
        <br><label id="result">label>
    form>
    <script>
        $("#submit").click(function() {
            $.ajax({
                url:"/calculate",
                type:"post",
                data:{
                    "width":$("#width").val(),
                    "height":$("#height").val(),
                    "size":$("#size").val(),
                    },
                    success:function(data){
                    let json = JSON.parse(data);
                    $("#result").text("屏幕像素密度为:" + json["PPI"] + "PPI");
                }
            });
        });
    script>
body>
html>

程序入口实现

package com.davieyang.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
//@SpringBootApplication 代表将程序作为SpringBoot应用来运行
public class Application {
    public static void main(String[] args){
        SpringApplication.run(Application.class, args);
        //调用run方法并传入当前Class作为参数来运行程序,同时传入main方法的args参数
    }
}

执行SpringBoot程序

"C:\Program Files\Java\jdk1.8.0_261\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2020.2\lib\idea_rt.jar=51816:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2020.2\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.8.0_261\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_261\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_261\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_261\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_261\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_261\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_261\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_261\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_261\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_261\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_261\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_261\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_261\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_261\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_261\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_261\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_261\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_261\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_261\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_261\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_261\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_261\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_261\jre\lib\rt.jar;D:\Programs\Java\SpringBootDemo\target\classes;E:\apache-maven-3.6.2\Repository\org\springframework\boot\spring-boot-starter\2.3.3.RELEASE\spring-boot-starter-2.3.3.RELEASE.jar;E:\apache-maven-3.6.2\Repository\org\springframework\boot\spring-boot\2.3.3.RELEASE\spring-boot-2.3.3.RELEASE.jar;E:\apache-maven-3.6.2\Repository\org\springframework\boot\spring-boot-autoconfigure\2.3.3.RELEASE\spring-boot-autoconfigure-2.3.3.RELEASE.jar;E:\apache-maven-3.6.2\Repository\org\springframework\boot\spring-boot-starter-logging\2.3.3.RELEASE\spring-boot-starter-logging-2.3.3.RELEASE.jar;E:\apache-maven-3.6.2\Repository\ch\qos\logback\logback-classic\1.2.3\logback-classic-1.2.3.jar;E:\apache-maven-3.6.2\Repository\ch\qos\logback\logback-core\1.2.3\logback-core-1.2.3.jar;E:\apache-maven-3.6.2\Repository\org\apache\logging\log4j\log4j-to-slf4j\2.13.3\log4j-to-slf4j-2.13.3.jar;E:\apache-maven-3.6.2\Repository\org\apache\logging\log4j\log4j-api\2.13.3\log4j-api-2.13.3.jar;E:\apache-maven-3.6.2\Repository\org\slf4j\jul-to-slf4j\1.7.30\jul-to-slf4j-1.7.30.jar;E:\apache-maven-3.6.2\Repository\jakarta\annotation\jakarta.annotation-api\1.3.5\jakarta.annotation-api-1.3.5.jar;E:\apache-maven-3.6.2\Repository\org\yaml\snakeyaml\1.26\snakeyaml-1.26.jar;E:\apache-maven-3.6.2\Repository\org\slf4j\slf4j-api\1.7.25\slf4j-api-1.7.25.jar;E:\apache-maven-3.6.2\Repository\org\springframework\spring-core\5.2.8.RELEASE\spring-core-5.2.8.RELEASE.jar;E:\apache-maven-3.6.2\Repository\org\springframework\spring-jcl\5.2.8.RELEASE\spring-jcl-5.2.8.RELEASE.jar;E:\apache-maven-3.6.2\Repository\org\springframework\boot\spring-boot-starter-web\2.3.3.RELEASE\spring-boot-starter-web-2.3.3.RELEASE.jar;E:\apache-maven-3.6.2\Repository\org\springframework\boot\spring-boot-starter-json\2.3.3.RELEASE\spring-boot-starter-json-2.3.3.RELEASE.jar;E:\apache-maven-3.6.2\Repository\com\fasterxml\jackson\core\jackson-databind\2.11.2\jackson-databind-2.11.2.jar;E:\apache-maven-3.6.2\Repository\com\fasterxml\jackson\core\jackson-annotations\2.11.2\jackson-annotations-2.11.2.jar;E:\apache-maven-3.6.2\Repository\com\fasterxml\jackson\core\jackson-core\2.11.2\jackson-core-2.11.2.jar;E:\apache-maven-3.6.2\Repository\com\fasterxml\jackson\datatype\jackson-datatype-jdk8\2.11.2\jackson-datatype-jdk8-2.11.2.jar;E:\apache-maven-3.6.2\Repository\com\fasterxml\jackson\datatype\jackson-datatype-jsr310\2.11.2\jackson-datatype-jsr310-2.11.2.jar;E:\apache-maven-3.6.2\Repository\com\fasterxml\jackson\module\jackson-module-parameter-names\2.11.2\jackson-module-parameter-names-2.11.2.jar;E:\apache-maven-3.6.2\Repository\org\springframework\boot\spring-boot-starter-tomcat\2.3.3.RELEASE\spring-boot-starter-tomcat-2.3.3.RELEASE.jar;E:\apache-maven-3.6.2\Repository\org\apache\tomcat\embed\tomcat-embed-core\9.0.37\tomcat-embed-core-9.0.37.jar;E:\apache-maven-3.6.2\Repository\org\glassfish\jakarta.el\3.0.3\jakarta.el-3.0.3.jar;E:\apache-maven-3.6.2\Repository\org\apache\tomcat\embed\tomcat-embed-websocket\9.0.37\tomcat-embed-websocket-9.0.37.jar;E:\apache-maven-3.6.2\Repository\org\springframework\spring-web\5.2.8.RELEASE\spring-web-5.2.8.RELEASE.jar;E:\apache-maven-3.6.2\Repository\org\springframework\spring-beans\5.2.8.RELEASE\spring-beans-5.2.8.RELEASE.jar;E:\apache-maven-3.6.2\Repository\org\springframework\spring-webmvc\5.2.8.RELEASE\spring-webmvc-5.2.8.RELEASE.jar;E:\apache-maven-3.6.2\Repository\org\springframework\spring-aop\5.2.8.RELEASE\spring-aop-5.2.8.RELEASE.jar;E:\apache-maven-3.6.2\Repository\org\springframework\spring-context\5.2.8.RELEASE\spring-context-5.2.8.RELEASE.jar;E:\apache-maven-3.6.2\Repository\org\springframework\spring-expression\5.2.8.RELEASE\spring-expression-5.2.8.RELEASE.jar;E:\apache-maven-3.6.2\Repository\org\springframework\boot\spring-boot-starter-thymeleaf\2.3.3.RELEASE\spring-boot-starter-thymeleaf-2.3.3.RELEASE.jar;E:\apache-maven-3.6.2\Repository\org\thymeleaf\thymeleaf-spring5\3.0.11.RELEASE\thymeleaf-spring5-3.0.11.RELEASE.jar;E:\apache-maven-3.6.2\Repository\org\thymeleaf\thymeleaf\3.0.11.RELEASE\thymeleaf-3.0.11.RELEASE.jar;E:\apache-maven-3.6.2\Repository\org\attoparser\attoparser\2.0.5.RELEASE\attoparser-2.0.5.RELEASE.jar;E:\apache-maven-3.6.2\Repository\org\unbescape\unbescape\1.1.6.RELEASE\unbescape-1.1.6.RELEASE.jar;E:\apache-maven-3.6.2\Repository\org\thymeleaf\extras\thymeleaf-extras-java8time\3.0.4.RELEASE\thymeleaf-extras-java8time-3.0.4.RELEASE.jar" com.davieyang.springboot.Application

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.3.3.RELEASE)

2020-08-18 19:34:24.269  INFO 402884 --- [           main] com.davieyang.springboot.Application     : Starting Application on DESKTOP-KEOVP72 with PID 402884 (D:\Programs\Java\SpringBootDemo\target\classes started by Administrator in D:\Programs\Java\SpringBootDemo)
2020-08-18 19:34:24.284  INFO 402884 --- [           main] com.davieyang.springboot.Application     : No active profile set, falling back to default profiles: default
2020-08-18 19:34:25.476  INFO 402884 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2020-08-18 19:34:25.489  INFO 402884 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-08-18 19:34:25.489  INFO 402884 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.37]
2020-08-18 19:34:25.575  INFO 402884 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2020-08-18 19:34:25.575  INFO 402884 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1222 ms
2020-08-18 19:34:25.772  INFO 402884 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2020-08-18 19:34:26.007  INFO 402884 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2020-08-18 19:34:26.016  INFO 402884 --- [           main] com.davieyang.springboot.Application     : Started Application in 2.205 seconds (JVM running for 2.749)
2020-08-18 19:34:34.661  INFO 402884 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-08-18 19:34:34.661  INFO 402884 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2020-08-18 19:34:34.671  INFO 402884 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 10 ms

查看执行结果

用浏览器打开http://localhost:8080/index即可看到如下页面
单元测试系列[v1.0.0][SpringBootTest]_第2张图片

测试Service层

package com.davieyang.springboot.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
//是一个抽象类,它是Spring Boot专为TestNG打造的
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import com.davieyang.springboot.Application;


@SpringBootTest(classes={Application.class})
//Spring Boot专为测试设计的注解,classes方法的作用是传入启动类
public class CalculatorForPpiServiceTest extends AbstractTestNGSpringContextTests
{
    @Autowired
    //类似于@Resource注解,不同的是@Autowired注解属于Spring框架,而@Resource注解不属于Spring框架
    private CalculatorForPpiService service;
    private int width;
    private int height;
    private double size;

    @BeforeClass
    public void init(){
        width=750;
        height=1334;
        size=4.7;
    }

    @Test
    public void testCase1(){
        Assert.assertEquals(326, service.calculate(width, height, size));
    }
    @Test
    public void testCase2(){
        Assert.assertEquals(-1, service.calculate(-1, height, size));
    }
    @Test
    public void testCase3(){
        Assert.assertEquals(-1, service.calculate(0, height, size));
    }
    @Test
    public void testCase4(){
        Assert.assertEquals(-1, service.calculate(width, -1, size));
    }
    @Test
    public void testCase5(){
        Assert.assertEquals(-1, service.calculate(width, 0, size));
    }
    @Test
    public void testCase6(){
        Assert.assertEquals(-1, service.calculate(width, height, -1));
    }
    @Test
    public void testCase7(){
        Assert.assertEquals(-1, service.calculate(width, height, 0));
    }
}

配置testng.xml



<suite name="All Test Suite">
    <test verbose="2" preserve-order="true" name="D:/Programs/Java/SpringBootDemo">
        <classes>
            <class name="com.davieyang.springboot.service.CalculatorForPpiServiceTest">
                <methods>
                    <include name="testCase1"/>
                    <include name="testCase2"/>
                    <include name="testCase3"/>
                    <include name="testCase4"/>
                    <include name="testCase5"/>
                    <include name="testCase6"/>
                    <include name="testCase7"/>
                methods>
            class>
        classes>
    test>
suite>

执行测试

11:44:47.287 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
11:44:47.358 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
11:44:47.455 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.davieyang.springboot.service.CalculatorForPpiServiceTest] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper]
11:44:47.507 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.davieyang.springboot.service.CalculatorForPpiServiceTest], using SpringBootContextLoader
11:44:47.528 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.davieyang.springboot.service.CalculatorForPpiServiceTest]: class path resource [com/davieyang/springboot/service/CalculatorForPpiServiceTest-context.xml] does not exist
11:44:47.529 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.davieyang.springboot.service.CalculatorForPpiServiceTest]: class path resource [com/davieyang/springboot/service/CalculatorForPpiServiceTestContext.groovy] does not exist
11:44:47.529 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [com.davieyang.springboot.service.CalculatorForPpiServiceTest]: no resource found for suffixes {-context.xml, Context.groovy}.
11:44:47.611 [main] DEBUG org.springframework.test.context.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [com.davieyang.springboot.service.CalculatorForPpiServiceTest]
11:44:47.842 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@38425407, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@43bc63a3, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@702657cc, org.springframework.test.context.support.DirtiesContextTestExecutionListener@6a6cb05c, org.springframework.test.context.event.EventPublishingTestExecutionListener@40a4337a]



11:44:47.924 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - Before test class: context [DefaultTestContext@ed7f8b4 testClass = CalculatorForPpiServiceTest, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@4c309d4d testClass = CalculatorForPpiServiceTest, locations = '{}', classes = '{class com.davieyang.springboot.Application, class com.davieyang.springboot.Application}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@3e77a1ed, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@1176dcec, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@19dc67c2, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@77e4c80f, org.springframework.boot.test.context.SpringBootTestArgs@1], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> true]], class annotated with @DirtiesContext [false] with mode [null].


11:44:47.960 [main] DEBUG org.springframework.test.context.support.TestPropertySourceUtils - Adding inlined properties to environment: {spring.jmx.enabled=false, org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.3.3.RELEASE)

2020-08-19 11:44:48.367  INFO 438900 --- [           main] c.d.s.s.CalculatorForPpiServiceTest      : Starting CalculatorForPpiServiceTest on DESKTOP-KEOVP72 with PID 438900 (D:\Programs\Java\SpringBootDemo\target\test-classes started by Administrator in D:\Programs\Java\SpringBootDemo)
2020-08-19 11:44:48.369  INFO 438900 --- [           main] c.d.s.s.CalculatorForPpiServiceTest      : No active profile set, falling back to default profiles: default
2020-08-19 11:44:49.602  INFO 438900 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2020-08-19 11:44:49.937  INFO 438900 --- [           main] c.d.s.s.CalculatorForPpiServiceTest      : Started CalculatorForPpiServiceTest in 1.958 seconds (JVM running for 3.47)

测试报告

单元测试系列[v1.0.0][SpringBootTest]_第3张图片

测试Controller层

package com.davieyang.springboot.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import com.davieyang.springboot.Application;


@SpringBootTest(classes = {Application.class})
public class CalculatorForPpiControllerTest extends AbstractTestNGSpringContextTests{
    @Autowired
    //使用@Autowired注解将要使用的的Controller注入当前类,这里使用的是Spring的Mock类的MockMvc
    //用它来模拟请求调用
    private CalculatorForPpiController controller;
    private MockMvc mock;
    private RequestBuilder request;
    private String width;
    private String height;
    private String size;

    @BeforeClass
    public void init(){
        mock = MockMvcBuilders.standaloneSetup(controller).build();
        //使用注入的Controller创建一个MockMvc实例,这里使用standaloneSetup()来创建,这种测试方式为独立测试方式
        //也可以使用webAppContextSetup()这种测试方式为集成Web测试方式
        width="750";
        height="1334";
        size="4.7";
    }

    @Test
    public void testCase1(){
        sendRequest(width, height, size, "326");
    }
    @Test
    public void testCase2(){
        sendRequest("-1", height, size, "-1");
    }
    @Test
    public void testCase3(){
        sendRequest("0", height, size, "-1");
    }
    @Test
    public void testCase4(){
        sendRequest(width, "-1", size, "-1");
    }
    @Test
    public void testCase5(){
        sendRequest(width, "0", size, "-1");
    }
    @Test
    public void testCase6(){
        sendRequest(width, height, "-1", "-1");
    }
    @Test
    public void testCase7(){
        sendRequest(width, height, "0", "-1");
    }

    private void sendRequest(String width, String height, String size, String expected){
        request = MockMvcRequestBuilders.post("/calculate").param("width", width).param("height", height).param("size", size);
        //使用MockMvcRequestBuilders构建一个请求对象,然后使用MockMvc对象调用该请求
        //然后使用andExpect()方法添加断言
        //在andExpect()方法中,通过提取后端返回的JSON与预期结果进行比较
        try{
            mock.perform(request).andExpect(MockMvcResultMatchers.jsonPath("PPI").value(expected));
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

配置testng.xml



<suite name="All Test Suite">
    <test verbose="2" preserve-order="true" name="D:/Programs/Java/SpringBootDemo">
        <classes>
            <class name="com.davieyang.springboot.controller.CalculatorForPpiControllerTest">
                <methods>
                    <include name="testCase1"/>
                    <include name="testCase2"/>
                    <include name="testCase3"/>
                    <include name="testCase4"/>
                    <include name="testCase5"/>
                    <include name="testCase6"/>
                    <include name="testCase7"/>
                methods>
            class>
            <class name="com.davieyang.springboot.service.CalculatorForPpiServiceTest">
                <methods>
                    <include name="testCase1"/>
                    <include name="testCase2"/>
                    <include name="testCase3"/>
                    <include name="testCase4"/>
                    <include name="testCase5"/>
                    <include name="testCase6"/>
                    <include name="testCase7"/>
                methods>
            class>
        classes>
    test>
suite>

执行测试

11:48:46.140 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
11:48:46.193 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
11:48:46.257 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.davieyang.springboot.controller.CalculatorForPpiControllerTest] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper]
11:48:46.273 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.davieyang.springboot.controller.CalculatorForPpiControllerTest], using SpringBootContextLoader
11:48:46.277 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.davieyang.springboot.controller.CalculatorForPpiControllerTest]: class path resource [com/davieyang/springboot/controller/CalculatorForPpiControllerTest-context.xml] does not exist
11:48:46.277 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.davieyang.springboot.controller.CalculatorForPpiControllerTest]: class path resource [com/davieyang/springboot/controller/CalculatorForPpiControllerTestContext.groovy] does not exist
11:48:46.277 [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}.
11:48:46.351 [main] DEBUG org.springframework.test.context.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [com.davieyang.springboot.controller.CalculatorForPpiControllerTest]
11:48:46.652 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@2d1ef81a, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@4c402120, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@327514f, org.springframework.test.context.support.DirtiesContextTestExecutionListener@5b12b668, org.springframework.test.context.event.EventPublishingTestExecutionListener@1165b38]
11:48:46.717 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
11:48:46.717 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
11:48:46.718 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.davieyang.springboot.service.CalculatorForPpiServiceTest] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper]
11:48:46.719 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.davieyang.springboot.service.CalculatorForPpiServiceTest], using SpringBootContextLoader
11:48:46.719 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.davieyang.springboot.service.CalculatorForPpiServiceTest]: class path resource [com/davieyang/springboot/service/CalculatorForPpiServiceTest-context.xml] does not exist
11:48:46.720 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.davieyang.springboot.service.CalculatorForPpiServiceTest]: class path resource [com/davieyang/springboot/service/CalculatorForPpiServiceTestContext.groovy] does not exist
11:48:46.720 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [com.davieyang.springboot.service.CalculatorForPpiServiceTest]: no resource found for suffixes {-context.xml, Context.groovy}.
11:48:46.723 [main] DEBUG org.springframework.test.context.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [com.davieyang.springboot.service.CalculatorForPpiServiceTest]
11:48:46.725 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@198b6731, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@7c6908d7, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@3c9754d8, org.springframework.test.context.support.DirtiesContextTestExecutionListener@3bf7ca37, org.springframework.test.context.event.EventPublishingTestExecutionListener@79079097]



11:48:46.766 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - Before test class: context [DefaultTestContext@6db9f5a4 testClass = CalculatorForPpiControllerTest, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@5f8edcc5 testClass = CalculatorForPpiControllerTest, locations = '{}', classes = '{class com.davieyang.springboot.Application, class com.davieyang.springboot.Application}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@4ba2ca36, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@6a79c292, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@58fdd99, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@6b53e23f, org.springframework.boot.test.context.SpringBootTestArgs@1], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> true]], class annotated with @DirtiesContext [false] with mode [null].


11:48:46.829 [main] DEBUG org.springframework.test.context.support.TestPropertySourceUtils - Adding inlined properties to environment: {spring.jmx.enabled=false, org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.3.3.RELEASE)

2020-08-19 11:48:47.210  INFO 439204 --- [           main] c.d.s.c.CalculatorForPpiControllerTest   : Starting CalculatorForPpiControllerTest on DESKTOP-KEOVP72 with PID 439204 (D:\Programs\Java\SpringBootDemo\target\test-classes started by Administrator in D:\Programs\Java\SpringBootDemo)
2020-08-19 11:48:47.212  INFO 439204 --- [           main] c.d.s.c.CalculatorForPpiControllerTest   : No active profile set, falling back to default profiles: default
2020-08-19 11:48:48.346  INFO 439204 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2020-08-19 11:48:48.660  INFO 439204 --- [           main] c.d.s.c.CalculatorForPpiControllerTest   : Started CalculatorForPpiControllerTest in 1.811 seconds (JVM running for 3.214)


2020-08-19 11:48:48.708  INFO 439204 --- [           main] o.s.mock.web.MockServletContext          : Initializing Spring TestDispatcherServlet ''
2020-08-19 11:48:48.708  INFO 439204 --- [           main] o.s.t.web.servlet.TestDispatcherServlet  : Initializing Servlet ''
2020-08-19 11:48:48.709  INFO 439204 --- [           main] o.s.t.web.servlet.TestDispatcherServlet  : Completed initialization in 0 ms

测试报告

单元测试系列[v1.0.0][SpringBootTest]_第4张图片

你可能感兴趣的:(单元测试-Java,SpringBoot,SpringBootTest,Mock,MockMvc,TestNG)