案例一   官方文档: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. Spring Cloud Gateway 服务网关快速上手

    Spring Cloud Gateway 服务网关 API 主流网关有NGINX.ZUUL.Spring Cloud Gateway.Linkerd等:Spring Cloud Gateway构建于 ...

  2. react父组件调用子组件中方法

  3. Unity进阶之ET网络游戏开发框架 06-游客登录

    版权申明: 本文原创首发于以下网站: 博客园『优梦创客』的空间:https://www.cnblogs.com/raymondking123 优梦创客的官方博客:https://91make.top ...

  4. Django-内置用户系统

    Django自带的用户认证 我们在开发一个网站的时候,无可避免的需要设计实现网站的用户系统.此时我们需要实现包括 1.用户注册 2.用户登录 3.用户认证 4.注销 5.修改密码 Django作为一个 ...

  5. 随笔编号-09 批量导入数据(Mysql)报MySQL server has gone away 问题的解决方法

    问题场景: 使用*.sql 脚本,批量导入数据到mysql实例中,使用DOS 界面导入的,期间,到最后一步 source D:\aaa.sql  回车后,系统提示 MySQL server has g ...

  6. 算法与数据结构基础 - 贪心(Greedy)

    贪心基础 贪心(Greedy)常用于解决最优问题,以期通过某种策略获得一系列局部最优解.从而求得整体最优解. 贪心从局部最优角度考虑,只适用于具备无后效性的问题,即某个状态以前的过程不影响以后的状态. ...

  7. Leetcode之回溯法专题-37. 解数独(Sudoku Solver)

    Leetcode之回溯法专题-37. 解数独(Sudoku Solver) 编写一个程序,通过已填充的空格来解决数独问题. 一个数独的解法需遵循如下规则: 数字 1-9 在每一行只能出现一次.数字 1 ...

  8. JavaScript清除空格、换行,把双引号转换成单引号

    1.页面 2.源码 <!DOCTYPE> <html> <head> <meta charset="utf-8"> <titl ...

  9. 01_liteide 集成环境运行的问题

    //go语言是以包为管理单位 //每个文件必须先声明包 //程序必须有一个main包 package main import (  "fmt" ) //入口函数 func main ...

  10. ES6之模块化导入导出

    1.概述 在js的历史上一直没有模块(module)体系,无法将一个大程序拆分成相互依赖的小文件,再用简单的方法拼装起来,这对开发大型的.复杂的项目形成了巨大障碍. 在 ES6 之前,社区制定了一些模 ...