案例一   官方文档: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. 2321. 【NOIP普及组T1】方程

    2321. [NOIP普及组T1]方程 时间限制: 1000 ms  空间限制: 262144 KB 题目描述

  2. git 常规业务场景 使用

    一般每个开发者都会有个自己的分支,有个test分支,合并代码用,两条分支相互备份,就算merge的时候被覆盖,也不用担心 建立自己的分支 // 创建本地分支, git checkout -b dev_ ...

  3. Spring-Boot:Profile简单示例

    //Resources目录下创建 application.properties spring.profiles.active=prod //Resources目录下创建 application-pro ...

  4. RestTemplate最详解

    目录 1. RestTemplate简单使用 2. 一些其他设置 3. 简单总结 在项目中,当我们需要远程调用一个HTTP接口时,我们经常会用到RestTemplate这个类.这个类是Spring框架 ...

  5. C#开发BIMFACE系列5 服务端API之文件直传

    BIMFACE使用了分布式对象存储来存储用户上传的模型/图纸文件.如使用普通的文件上传接口, 文件流会通过BIMFACE的服务器,再流向最终的分布式存储系统,整个上传过程会受BIMFACE服务器的带宽 ...

  6. egret之好友列表(滑动列表)

    本文采用List+Scroller实现列表滑动功能 首先新建两个皮肤,一个用做好友界面的显示,一个用作单个好友的显示,新建皮肤如下: 皮肤一取名为:wxMainSkin,添加如下控件 皮肤一取名为:w ...

  7. ES5新增数组方法测试和字符串常见API测试

    首先是ES5新增数组方法测试: <!DOCTYPE html><html lang="en"><head> <meta charset=& ...

  8. Java 前后端分离项目:微人事

    本文适合刚学习完 Java 语言基础的人群,跟着本文可了解和运行项目,本示例是在 Windows 操作系统下演示. 本文作者:HelloGitHub-秦人 大家好!这里是 HelloGitHub 推出 ...

  9. ASP.NET Core 3.0中使用动态控制器路由

    原文:Dynamic controller routing in ASP.NET Core 3.0 作者:Filip W 译文:https://www.cnblogs.com/lwqlun/p/114 ...

  10. MSSql 保留两位小数的用法

    --MSSql 保留两位小数的用法1: round(@sum,2),2: Convert(decimal(18,2),@sum) select round(9,2)                  ...