MockBean 单元测试
案例一 官方文档:https://docs.spring.io/spring-boot/docs/2.0.4.RELEASE/reference/htmlsingle/ import org.junit.*; import org.junit.runner.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.boot.test.autoconfigure.web.servlet.*;
import org.springframework.boot.test.mock.mockito.*; import static org.assertj.core.api.Assertions.*;
import static org.mockito.BDDMockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @RunWith(SpringRunner.class)
/**使用webMvcTest工具测试,UserVehicleControkker.class代表对UserVehicleControkker 进行测试*/
@WebMvcTest(UserVehicleController.class)
public class MyControllerTests { @Autowired
private MockMvc mvc; @MockBean
private UserVehicleService userVehicleService; @Test
public void testExample() throws Exception {
given(this.userVehicleService.getVehicleDetails("sboot"))
.willReturn(new VehicleDetails("Honda", "Civic"));
this.mvc.perform(get("/sboot/vehicle").accept(MediaType.TEXT_PLAIN))
.andExpect(status().isOk()).andExpect(content().string("Honda Civic"));
} } 案例二:jsons数据的传递,即传一个对象 官方文档的推荐:
import org.junit.*;
import org.junit.runner.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.boot.test.autoconfigure.json.*;
import org.springframework.boot.test.context.*;
import org.springframework.boot.test.json.*;
import org.springframework.test.context.junit4.*; import static org.assertj.core.api.Assertions.*; @RunWith(SpringRunner.class)
@JsonTest
public class MyJsonTests { @Autowired
private JacksonTester<VehicleDetails> json;
/**方式一/
@Test
public void testSerialize() throws Exception {
VehicleDetails details = new VehicleDetails("Honda", "Civic");
// Assert against a `.json` file in the same package as the test
assertThat(this.json.write(details)).isEqualToJson("expected.json");
// Or use JSON path based assertions
assertThat(this.json.write(details)).hasJsonPathStringValue("@.make");
assertThat(this.json.write(details)).extractingJsonPathStringValue("@.make")
.isEqualTo("Honda");
}
/**方式二/
@Test
public void testDeserialize() throws Exception {
/**自己制作一些json数据*/
String content = "{\"make\":\"Ford\",\"model\":\"Focus\"}";
/**使用预言:第一个:assertThat进行数据的json格式的转换,以及传递数据*/
assertThat(this.json.parse(content)) .isEqualTo(new VehicleDetails("Ford", "Focus"));
/**使用预言:assertThat:传递数据,并得到自己制作的数据,并且期望返回的数据是否是 “Ford”*/
assertThat(this.json.parseObject(content).getMake()).isEqualTo("Ford");
}
}
/*个人的json数据:包装成一个对象,传递过去*/
1):需要的依赖:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.12</version>
</dependency>
2):
源代码:
package hsbc.team03.ordersystem.displayproduct; import com.alibaba.fastjson.JSONObject;
import hsbc.team03.ordersystem.displayproduct.common.UUIDUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
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.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext; import java.util.ArrayList;
import java.util.List; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /**
* @Author:Evan
* @Date:2018/8/7 11:01
* @Describe:
* @Return:
* @Param:
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class ManagerControllerTest {
@Autowired
private WebApplicationContext context;
private MockMvc mvc; /**使用mockBean模拟ManagerServiceImpl层 ,注意ManagerServiceImpl 是自己创建的一个类*/
@MockBean
private ManagerServiceImpl managerServiceImpl; @Before
public void setUp() {
mvc = MockMvcBuilders.webAppContextSetup(context).build();
}
@Test
public void managerAddProduct() throws Exception {
Mockito.when(managerServiceImpl.addProduct(Mockito.any(Product.class))).thenReturn(true); /**制造数据,即对象*/
Product product = new Product();
product.setId(UUIDUtils.getUUID());
product.setProductCode("231701");
product.setProductName("中海");
product.setProductPrice(20.8);
product.setProductType("稳健型");
product.setDescription("这是1");
product.setStatus(1);
product.setProductDeadline("2018-8-10"); /**将对象进行转换成json格式*/
String requestJson = JSONObject.toJSONString(product); mvc.perform(
/**post方法、访问的路径*/
post("/manager/add/products")
.contentType(MediaType.APPLICATION_JSON_UTF8) /*数据格式*/
.content(requestJson) /*内容,即参数*/
.accept(MediaType.APPLICATION_JSON)) /*接收返回的参数是json格式*/
.andExpect(status().isOk()) /*status().isOk(),期望返回的状态码是200*/
.andDo(print()); /*控制台打印*/ }
}
MockBean 单元测试的更多相关文章
- Springboot单元测试(MockBean||SpyBean)
转载:https://blog.csdn.net/maiyikai/article/details/78483423 本来要写springboot集成netty实现的,但是想起来单元测试没总结,那就趁 ...
- 如何编写单元测试-基于Spring
单元测试 首先单元测试真的算是一种"脏活累活",但是我个人感觉还是有必要,至少本人最近开始写单元测试后还是能发现一些"bug"的. 如何写单元测试 单元测试的要 ...
- SpringBoot系列: 单元测试2
之前发了SpringBoot 单元测试的博客, https://www.cnblogs.com/harrychinese/p/springboot_unittesting.html , 内容较少, 现 ...
- 学习 Spring Boot:(二十九)Spring Boot Junit 单元测试
前言 JUnit 是一个回归测试框架,被开发者用于实施对应用程序的单元测试,加快程序编制速度,同时提高编码的质量. JUnit 测试框架具有以下重要特性: 测试工具 测试套件 测试运行器 测试分类 了 ...
- 教育单元测试mock框架优化之路(中)
转载:https://sq.163yun.com/blog/article/169564470918451200 三.间接依赖的bean的mock替换 对于前面提供的@Mock,@Spy+@Injec ...
- Spring Boot 2 实践记录之 封装依赖及尽可能不创建静态方法以避免在 Service 和 Controller 的单元测试中使用 Powermock
在前面的文章中(Spring Boot 2 实践记录之 Powermock 和 SpringBootTest)提到了使用 Powermock 结合 SpringBootTest.WebMvcTest ...
- 基于spring-boot的应用程序的单元测试方案
概述 本文主要介绍如何对基于spring-boot的web应用编写单元测试.集成测试的代码. 此类应用的架构图一般如下所示: 我们项目的程序,对应到上图中的web应用部分.这部分一般分为Control ...
- spring boot test MockBean
使用spring boot , MockBean @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class) p ...
- SpringBoot重点详解--使用Junit进行单元测试
目录 添加依赖与配置 ApplicationContext测试 Environment测试 MockBean测试 Controller测试 情况一 情况二 方法一 方法二 本文将对在Springboo ...
随机推荐
- PostgreSQL入门教程(命令行)
初次安装完成后 1.默认生成一个名为postgres的数据库 2.一个名为postgres的数据库用户 3.这里需要注意的是,同时还生成了一个名为postgres的Linux系统用户. 下面,我们使用 ...
- FileUtils工具类的使用
import org.apache.commons.io.FileUtils; import org.apache.commons.io.filefilter.DirectoryFileFilter; ...
- Oracle面对“数据倾斜列使用绑定变量”场景的解决方案
1.背景知识介绍 2.构造测试用例 3.场景测试 4.总结 1.背景知识介绍 我们知道,Oracle在传统的OLTP(在线事务处理)类系统中,强烈推荐使用绑定变量,这样可以有效的减少硬解析从而 ...
- Java描述表达式求值的两种解法:双栈结构和二叉树
Java描述表达式求值的两种解法:双栈结构和二叉树 原题大意:表达式求值 求一个非负整数四则混合运算且含嵌套括号表达式的值.如: # 输入: 1+2*(6/2)-4 # 输出: 3.0 数据保证: 保 ...
- netty无缝切换rabbitmq、activemq、rocketmq实现聊天室单聊、群聊功能
netty的pipeline处理链上的handler:需要IdleStateHandler心跳检测channel是否有效,以及处理登录认证的UserAuthHandler和消息处理MessageHan ...
- ECMAScript---布尔类型、null、undefined详解
布尔类型中 至只有 true和false 在开发中它是非常重要的两个值,尤其是在条件判断中 如何把其他类型转换为布尔类型? 1.Boolean() Boolean(1); //true Boolean ...
- MSIL实用指南-生成for语句
for语句格式是这样的for(<初始化语句>;<条件语句>;<自增减语句>) <循环体> 它可以转换为while语句 if(<条件语句>){ ...
- codeblocks中文乱码原因及解决办法
原因:(本地化做得不够好)默认情况下codeblocks编辑器保存源文件是保存为windows本地编码,就是WINDOWS-936字符集,即GBK:但CB的编辑器在默认编辑的时候是按照UTF-8来解析 ...
- 基于Taro与Typescript开发的网易云音乐小程序
基于Taro与网易云音乐api开发,技术栈主要是:typescript+taro+taro-ui+redux,目前主要是着重小程序端的展示,主要也是借此项目强化下上述几个技术栈的使用,通过这个项目也可 ...
- 再谈C#装箱和拆箱操作
1. 使用非泛型集合时引发的装箱和拆箱操作 看下面的一段代码: 1 2 3 4 5 6 7 8 var array = new ArrayList(); array.Add(1); array.Add ...