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 ...
随机推荐
- vSphere Web Client 监控 esxi 主机硬件状态
开启插件能对 vcenter 管理的 esxi 主机的硬件状态进行监控. 以下操作均在 vcenter 主机上操作. 0x00 修改配置 文档中关于启用脚本插件支持的说明: Enabling Scri ...
- (九)c#Winform自定义控件-树
前提 入行已经7,8年了,一直想做一套漂亮点的自定义控件,于是就有了本系列文章. 开源地址:https://gitee.com/kwwwvagaa/net_winform_custom_control ...
- NVIDIA: Failed to initialize NVML: driver/library version mismatch
[NVIDIA驱动:Failed to initialize NVML: driver/library version mismatch] 原因:Ubuntu16.04 装新驱动时,会报以上错误,定位 ...
- npm钉钉脚手架,支持考勤信息获取
钉钉官方并未提供nodejs包,第一次调用接口的时候非常费事,而且尝试去寻找相关的钉钉考勤数据模块的时候只找到了一些消息啊,只能办公啊,免登啊之类的模块,有关考勤数据的似乎没有 关于dd的npm包中一 ...
- 盘一盘 NIO (三)—— Selector解析
Selector是个啥? Selector是Java NIO核心组件中的选择器,用于检查一个或多个Channel(通道)的状态是否处于可读.可写.实现一个单独的线程可以管理多个channel,从而管理 ...
- vue项目中引入Sass
Sass作为目前成熟,稳定,强大的css扩展语言,让越来越多的前端工程师喜欢上它.下面介绍了如何在vue项目 中引入Sass. 首先在项目文件夹执行命令 npm install vue-cli -g, ...
- [WPF自定义控件库] 关于ScrollViewr和滚动轮劫持(scroll-wheel-hijack)
1. 什么是滚动轮劫持 这篇文章介绍一个很简单的继承自ScrollViewer的控件: public class ExtendedScrollViewer : ScrollViewer { prote ...
- java两个对象属性比较
两个对象进行比较相等,有两种做法: 1,情况一:当仅仅只是判断两个对象是否相等时,只需重写equals()方法即可.这里就不用说明 2.情况二:当除了情况一之外,还需知道是那个属性不同,那么就需要采用 ...
- python 24 封装、多态
目录 1. 封装.多态 2. 鸭子类型--Duck typing 3. 类的约束 5. super深度剖析 1. 封装.多态 封装:将代码.数据放入一个容器空间中,并且可以使用. 多态:一个事物可以呈 ...
- Python+Selenium - Web自动化测试(二):元素定位
前言 前面已经把环境搭建好了,现在开始使用 Selenium 中的 Webdriver 框架编写自动化代码脚本,我们常见的在浏览器中的操作都会有相对应的类方法,这些方法需要定位才能操作元素,不同网页的 ...