案例一   官方文档: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 单元测试的更多相关文章

  1. Springboot单元测试(MockBean||SpyBean)

    转载:https://blog.csdn.net/maiyikai/article/details/78483423 本来要写springboot集成netty实现的,但是想起来单元测试没总结,那就趁 ...

  2. 如何编写单元测试-基于Spring

    单元测试 首先单元测试真的算是一种"脏活累活",但是我个人感觉还是有必要,至少本人最近开始写单元测试后还是能发现一些"bug"的. 如何写单元测试 单元测试的要 ...

  3. SpringBoot系列: 单元测试2

    之前发了SpringBoot 单元测试的博客, https://www.cnblogs.com/harrychinese/p/springboot_unittesting.html , 内容较少, 现 ...

  4. 学习 Spring Boot:(二十九)Spring Boot Junit 单元测试

    前言 JUnit 是一个回归测试框架,被开发者用于实施对应用程序的单元测试,加快程序编制速度,同时提高编码的质量. JUnit 测试框架具有以下重要特性: 测试工具 测试套件 测试运行器 测试分类 了 ...

  5. 教育单元测试mock框架优化之路(中)

    转载:https://sq.163yun.com/blog/article/169564470918451200 三.间接依赖的bean的mock替换 对于前面提供的@Mock,@Spy+@Injec ...

  6. Spring Boot 2 实践记录之 封装依赖及尽可能不创建静态方法以避免在 Service 和 Controller 的单元测试中使用 Powermock

    在前面的文章中(Spring Boot 2 实践记录之 Powermock 和 SpringBootTest)提到了使用 Powermock 结合 SpringBootTest.WebMvcTest ...

  7. 基于spring-boot的应用程序的单元测试方案

    概述 本文主要介绍如何对基于spring-boot的web应用编写单元测试.集成测试的代码. 此类应用的架构图一般如下所示: 我们项目的程序,对应到上图中的web应用部分.这部分一般分为Control ...

  8. spring boot test MockBean

    使用spring boot , MockBean @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class) p ...

  9. SpringBoot重点详解--使用Junit进行单元测试

    目录 添加依赖与配置 ApplicationContext测试 Environment测试 MockBean测试 Controller测试 情况一 情况二 方法一 方法二 本文将对在Springboo ...

随机推荐

  1. Zabbix数据库空间大小使用计算

    一.Zabbix的数据存储主要分类 1.历史数据 2.趋势数据 3.事件数据 二.每秒处理的数据量 顾名思义,例如,有3000个监控项(item),每60秒取一次值,即平均每秒有50(3000/60) ...

  2. 【Spring Boot】利用 Spring Boot Admin 进行项目监控管理

    利用 Spring Boot Admin 进行项目监控管理 一.Spring Boot Admin 是什么 Spring Boot Admin (SBA) 是一个社区开源项目,用于管理和监视 Spri ...

  3. 图数据库 Nebula Graph 的数据模型和系统架构设计

    Nebula Graph:一个开源的分布式图数据库.作为唯一能够存储万亿个带属性的节点和边的在线图数据库,Nebula Graph 不仅能够在高并发场景下满足毫秒级的低时延查询要求,而且能够提供极高的 ...

  4. java 判断 string 转 integer 判断

    NumberUtils.isDigits("1") NumberUtils.isDigits("/") 根据返回 true false 再确定是否转换即可 需要 ...

  5. Qt无边框窗体-最大化时支持拖拽还原

    目录 一.概述 二.效果展示 三.demo制作 1.设计窗体 2.双击放大 四.拖拽 五.相关文章 原文链接:Markdown模板 一.概述 用Qt进行开发界面时,既想要实现友好的用户交互又想界面漂亮 ...

  6. HTML5 storage事件监听

    引用<h5移动web开发指南>上的话: “当同源页面的某个页面修改了localStorage,其余的同源页面只要注册了storage事件,就会触发” 所以,localStorage  st ...

  7. Codeforces 976E

    题意略. 思路: 容易知道那a次倍增放在同一个怪身上是最优的,其余的怪我们只需要取hp值和damage值中间最大的那个就好了(在b值的限制下). 然而我们并不知道把那a次倍增放在哪个怪身上最好,那么我 ...

  8. 关于post和get的区别

    首先,get和post并没有本质上的区别,都只是 HTTP 协议中两种请求方式,用的都是同一个传输层协议,在传输上并没有什么不同.     1.get和post报文上的区别 GET 和 POST 只是 ...

  9. 04_枚举类型iota

    iota是枚举类型的关键字,使用iota可以方便快捷的给常量赋值,主要体现在以下几个方面:1.iota常量自动生成器,每个一行加12.iota给常量赋值使用3.iota遇到const重置为04.可以写 ...

  10. Unity的UGUI在SetParent后修改UI的localposition问题

    正常情况下,UGUI设置UI的localposition可以直接赋值 UIxxx.rectTransform.localPosition = ] / 2f, , ); 运行后在Unity的Inspec ...