此处的Unit Test in SpringBoot 包括:

SpringApplication Test

Service Test

ControllerTest

测试项目结构如下:

代码如下:

POM.xml

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.study</groupId>
<artifactId>SpringBootTest-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>SpringBootTest-2</name>
<description>Demo project for Spring Boot</description> <properties>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>
package com.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication
public class Application { public static void main(String[] args) {
SpringApplication.run(Application.class, args);
} }
package com.app;

public class Book {

    private Integer id;
private String name;
private String author; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getAuthor() {
return author;
} public void setAuthor(String author) {
this.author = author;
} public String toString() {
return String.format("Book - id: %d, name: %s, author: %s", id,name,author);
} }
package com.app;

import java.awt.print.Book;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController; @RestController
public class Controller { @Autowired
HelloService helloService; @GetMapping("/hello")
public String sayHi(String name) {
return helloService.sayHello(name);
} @PostMapping("/book")
public String addBook(@RequestBody Book book) {
return book.toString();
} }
package com.app;

import org.springframework.stereotype.Service;

@Service
public class HelloService { public String sayHello(String name) {
return "Hello " + name + "!";
}
}

UnitTest

package com.app;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class)
public class ApplicationTests { @Test
public void contextLoads() {
} }
package com.app;

import org.junit.Assert;
import org.junit.Before;
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.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext; import com.fasterxml.jackson.databind.ObjectMapper; @RunWith(SpringRunner.class)
@SpringBootTest
public class ControllerTest {
MockMvc mvc; @Autowired //模拟ServletContext环境
WebApplicationContext webApplicationContext; @Autowired
HelloService helloService; @Before
public void before() {
mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
} @Test
public void sayHiTest() throws Exception {
String uri = "/hello";
MvcResult mvcResult = mvc
.perform(MockMvcRequestBuilders.get(uri).contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("name", "World"))
.andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcResultHandlers.print()) // 可以查看Request被处理的细节
.andReturn();
String content = mvcResult.getResponse().getContentAsString();
String expectedContent = "Hello World!";
Assert.assertEquals("错误,返回值和预期返回值不一致", expectedContent, content);
} @Test
public void addBookTest() throws Exception {
ObjectMapper om = new ObjectMapper();
Book book = new Book();
book.setAuthor("罗贯中");
book.setName("三国演义");
book.setId(1); String param = om.writeValueAsString(book);
String uri = "/book";
MvcResult mvcResult = mvc
.perform(MockMvcRequestBuilders.post(uri).contentType(MediaType.APPLICATION_JSON).content(param))
.andExpect(MockMvcResultMatchers.status().isOk()).andReturn(); String content = mvcResult.getResponse().getContentAsString();
System.out.println(content); } }
package com.app;

import 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.boot.test.web.client.TestRestTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ControllerTestUseTestRestTemplate { /**
* 如果要使用TestRestTemplate进行测试,需要将@SPringBootTest 中webEnvironment属性的默认值由
* WebEnvironment.MOCK 修改为 WebEnvironment.DEFINED_PORT 或者 WebEnvironment.RANDOM_PORT
* 因为这两种都是使用一个真实的Servlet环境而不是模拟的Servlet环境
*/
@Autowired
TestRestTemplate restTemplate; @Test
public void sayHiTest2() { ResponseEntity<String> response = restTemplate.getForEntity("/hello?name={0}", String.class, "World");
String expectedContent = "Hello World!";
String content = response.getBody();
Assert.assertEquals("错误,返回值和预期返回值不一致", expectedContent, content);
} }
package com.app;

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; import org.junit.Assert; @RunWith(SpringRunner.class)
@SpringBootTest
public class HelloServiceTest { @Autowired
HelloService helloService; @Test
public void sayHelloTest() {
String hello = helloService.sayHello("World");
Assert.assertEquals(hello, "Hello World!");
} }
package com.app;

import java.io.IOException;

import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.json.JsonTest;
import org.springframework.boot.test.json.JacksonTester;
import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class)
@JsonTest //该注解将自动配置Jackson ObjectMapper @JsonComponent 以及 Jackson Modules
public class JSONTest { @Autowired
JacksonTester<Book> jacksonTester; @Test
public void testSerialize() throws IOException {
Book book = new Book();
book.setAuthor("罗贯中");
book.setName("三国演义");
book.setId(1); Assertions.assertThat(jacksonTester.write(book)).isEqualToJson("book.json");
Assertions.assertThat(jacksonTester.write(book)).hasJsonPathStringValue("@.name");
Assertions.assertThat(jacksonTester.write(book)).extractingJsonPathStringValue("@.name").isEqualTo("三国演义");
} @Test
public void testDeserialize() throws IOException {
String content = "{ \"id\": 1, \"name\": \"三国演义\", \"author\": \"罗贯中\" }";
Assertions.assertThat(jacksonTester.parseObject(content).getName()).isEqualTo("三国演义");
}
}
package com.app;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses; /**
* https://www.guru99.com/create-junit-test-suite.html
*
*/
@RunWith(Suite.class)
@SuiteClasses({ApplicationTests.class, ControllerTest.class, ControllerTestUseTestRestTemplate.class,
HelloServiceTest.class, JSONTest.class})
public class SuiteTests { }

book.json

{ "id": 1, "name": "三国演义", "author": "罗贯中" }
SuiteTests 的测试结果:
 

Unit Test in SpringBoot的更多相关文章

  1. SpringBoot vue

    springboot 整合vue就行前后端完全分离,监听器,过滤器,拦截器 https://github.com/ninuxGithub/spring-boot-vue-separateA blog ...

  2. 第三章 springboot + jedisCluster(转载)

    本编博客转发自:http://www.cnblogs.com/java-zhao/p/5347703.html 如果使用的是redis2.x,在项目中使用客户端分片(Shard)机制. 如果使用的是r ...

  3. 第三章 springboot + jedisCluster

    如果使用的是redis2.x,在项目中使用客户端分片(Shard)机制.(具体使用方式:第九章 企业项目开发--分布式缓存Redis(1)  第十章 企业项目开发--分布式缓存Redis(2)) 如果 ...

  4. SpringBoot 整合Ehcache3

    SpringBootLean 是对springboot学习与研究项目,是依据实际项目的形式对进行配置与处理,欢迎star与fork. [oschina 地址] http://git.oschina.n ...

  5. linux小白成长之路10————SpringBoot项目部署进阶

    [内容指引] war包部署: jar包部署: 基于Docker云部署. 一.war包部署 通过"云开发"平台初始化的SpringBoot项目默认采用jar形式打包,这也是我们推荐的 ...

  6. SpringBoot开发案例之多任务并行+线程池处理

    前言 前几篇文章着重介绍了后端服务数据库和多线程并行处理优化,并示例了改造前后的伪代码逻辑.当然了,优化是无止境的,前人栽树后人乘凉.作为我们开发者来说,既然站在了巨人的肩膀上,就要写出更加优化的程序 ...

  7. SpringBoot标准Properties

    # =================================================================== # COMMON SPRING BOOT PROPERTIE ...

  8. springboot application.properties 常用完整版配置信息

    从springboot官方文档中扒出来的,留存一下以后应该会用到 # ================================================================= ...

  9. 将自己的SpringBoot应用打包发布到Linux下Docker中

    目录 将自己的SpringBoot应用打包发布到Linux下Docker中 1. 环境介绍 2. 开始前的准备 2.1 开启docker远程连接 2.2 新建SpringBoot项目 3. 开始构建我 ...

随机推荐

  1. API 网关性能比较:NGINX vs. ZUUL vs. Spring Cloud Gateway vs. Linkerd

    前几天拜读了 OpsGenie 公司(一家致力于 Dev & Ops 的公司)的资深工程师 Turgay Çelik 博士写的一篇文章(链接在文末),文中介绍了他们最初也是采用 Nginx 作 ...

  2. java之设计模式汇总

    1.单例模式 就是一个类只产生一个对象 对应数据库连接 定时执行者服务(ScheduledExecutorService) 在整个项目中应该只有一个对象 2.工厂模式 定义一个用于创建对象的接口 让子 ...

  3. ubuntu16.04 Installing PHP 7.2

    //install sudo add-apt-repository ppa:ondrej/php sudo apt-get update sudo apt-get install php7.2 //C ...

  4. python的加密方式

    MD5加密 这是一种使用非常广泛的加密方式,不可逆的,在日常字符串加密中经常会用到,下面我简单介绍一下这种方式,主要用到Python自带的模块hashlib,测试代码如下,先创建一个md5对象,然后直 ...

  5. 欧拉系统-登陆 SSH 出现 Access Denied 错误

    1./home 权限问题如果 /home 只支持 root 访问,那么不妨试一下 /tmp ,然后用 mv 命令再转移 2./etc/ssh/sshd_config 配置问题     vi  /etc ...

  6. oracle存储过程临时表

    接到一个以前领导的需求,说的大概意思是: 如果能关联上就取关联上的最大值更新到表里,没有关联上的就取原来的值. 写一个存储过程,这正好用到了临时表,上网查询,用的太乱了,特别记录. 准备阶段 创建PD ...

  7. 利用druid sql parser搞一些事情

    在最近的项目开发中,有这样一个需求,就是给定一个查询的sql,在where语句中添加几个条件语句.刚开始想的是,是否能用正则去做这个事情呢?其实不用语法树还是有一点困难的. 经过一系列google,看 ...

  8. JVM内存区域划分总结

    发现网上有两个版本的JVM内存划分,一个是按照<深入理解JVM虚拟机>上的版本,包含程序计数器等,按照是否线程共享划分. 另一个我觉得更好记一些,也更适合我自己,在这里记录一下. 首先上思 ...

  9. 第十篇.6、python并发编程之IO模型

    一 IO模型介绍 为了更好地了解IO模型,我们需要事先回顾下:同步.异步.阻塞.非阻塞 同步(synchronous) IO和异步(asynchronous) IO,阻塞(blocking) IO和非 ...

  10. BLE 5协议栈-物理层

    文章转载自:http://www.sunyouqun.com/2017/04/page/4/ 1. 简介 物理层(Physical Layer)是BLE协议栈最底层,它规定了BLE通信的基础射频参数, ...