• 7
  • 6
分享

创建SpringBoot项目

1.jpg

配置pom

<?xml version="1.0" encoding="UTF-8"?>
<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.0</modelVersion>
  <groupId>com.davieyang</groupId>
  <artifactId>SpringBootDemo</artifactId>
  <version>1.0-SNAPSHOT</version>
  <name>SpringBootDemo</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>
  <dependencies>
    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-test -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <version>2.3.3.RELEASE</version>
      <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
      <version>2.3.3.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
      <version>2.3.3.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-parent -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>2.3.3.RELEASE</version>
      <type>pom</type>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.testng/testng -->
    <dependency>
      <groupId>org.testng</groupId>
      <artifactId>testng</artifactId>
      <version>6.14.3</version>
      <scope>test</scope>
    </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层]

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <meta charset="UTF-8">
    <title>CalculatorForPpi</title>
</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即可看到如下页面

图2.png

测试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

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<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)

测试报告

图3.png

测试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

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<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

测试报告

图4.png


作者:Davieyang.D.Y

原文链接:https://blog.csdn.net/dawei_yang000000/article/details/108091023#comments_13178319

  • 【留下美好印记】
    赞赏支持
登录 后发表评论
+ 关注

热门文章

    最新讲堂

      • 推荐阅读
      • 换一换
          •   随着分布式建设工作的推进,核心系统正在逐步下移,分布式系统不但降低成本,具有比集中式更佳的性能,同时也便于系统扩展、维护。分布式统一入口系统在整个系统中担任类似网关的角色,为不同请求提供统一入口,验证请求合法性、安全性,转换请求报文的格式等功能,将请求按照策略转发到其他分布式系统处理请求。由于分布式系统之间需要相互调用、转发,才能正常完成业务需求,为了避免分布式核心系统之间相互调用造成的连带影响,保护分布式统一入口系统及其他关联分布式核心系统,提供交易级、微服务级、子系统级等5种维度的流量控制方案,主要针对TCP请求进行流量控制,流量控制采用配置中心配置、文件配置两种方式,实现对交易请求的...
            14 15 706
            分享
          • 一、TCP协议简介 因特网的运输层在应用程序断点之间传送应用程序报文,在这一层主要有两种传输协议 TCP和 UDP,利用这两种协议能够传输报文。TCP 协议的全称是 Transmission Control Protocol 的缩写,意思是传输控制协议,HTTP底层采用TCP 作为通信协议,这是因为 TCP 是一种可靠的协议,保证通讯的数据不丢失。TCP协议提供面向连接的服务,它能够控制并确认报文能够准确送达,并提供了拥塞机制来控制网络传输,因此当网络拥塞时,会抑制其传输速率。TCP,提供面向连接的服务,在传送数据之前必须先建立连接,数据传送完成后要释放连接。因此TCP是一种十分可靠...
            0 0 1522
            分享
          •   假如你是一位测试主管,去评价一名测试工程师是否优秀,那么你将如何去判断呢?你最看重的是哪方面的能力呢?  对于这个问题,是不能一概而论的,要分为两种情况,情况不同,答案一定是不同的。  我先给你举个例子,听完这个例子之后,你就知道我为什么这样说了。  你去商场买一件东西,比如说手机,首先你会选择正规大商场去购买,然后会选择大品牌。  为什么这么说呢,因为你肯定知道,选购手机的时候,只能短暂的体验,想全方面了解,只能买到手里以后慢慢用才行。所以,手机的品牌、口碑、产品参数等等这些能看得到的数据就是重要的参考依据了。  但是,一旦买到手,成为了你的手机之后,你的想法立马会不同。你会希望它好用、...
            0 0 1051
            分享
          • 摘要:通过自动化技术简化测试工作的一个工具是Selenium。阅读更多内容,了解web自动化测试的好处,以及为什么Selenium可以成为帮助不同规模和行业的组织进行web自动化测试过程的解决方案的最终选择。你如何确保你的网站提供一致的结果,并帮助你的客户参与到这个数字时代?即使你已经在创建一个包含详细功能的网站上投入了大量资金,高级的网站测试是唯一让你有信心和保证你的网站在功能和性能方面如预期的那样运行的方法。更具体地说,web应用程序测试是一种允许你识别网站主要问题的实践。通常,这些问题与UI(任何影响用户体验的东西)、安全漏洞(敏感数据暴露、不安全组件等)以及兼容性或性能瓶颈(兼容性问题...
            1 0 1187
            分享
          • 背景:  提起随机自动化操作,相信大家并不陌生,目前使用最为普遍的adb monkey命令应该都有所耳闻。monkey优点不言而喻,它使用起来很简单,只需要在命令输入命令即可完成对app的各种随机操作,期间发现的崩溃也会捕获记录下来。但是在搜狗手机输入法项目中,这一方法就有些局限了:  1.输入法稳定性测试重点之一是输入各种语料内容,也就是输入ni'hao等比较有规律的词语,这一点monkey无法满足。  2.输入法稳定性测试需要定制有一些有序的动作,例如:输入ni'hao后,点击候选词文字进行上屏;又或者是切换输入键盘等。  3.以上2中定制的动作数量很多,希望能够在测试前进...
            0 0 2977
            分享
      • 51testing软件测试圈微信