最近使用Mockito完成了几个简单的测试,写个博客mark一下:

  第一种模拟web请求

  

@SpringBootTest
@RunWith(SpringRunner.class)
@WebAppConfiguration //测试环境使用,用来表示测试环境使用的ApplicationContext将是WebApplicationContext类型的;value指定web应用的根
public class ControllerTest {
private static final Logger logger = LogManager.getLogger(ControllerTest.class); @Autowired
private WebApplicationContext context; @Mock
private UserInfoService userInfoService; private MockMvc mockMvc; /**
* 构造MockMvc
* @throws Exception
*/
@Before
public void setupMockMvc() throws Exception {
// 初始化Mock
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
} /**
* 模拟add请求
*/
@Test
public void insertUserInfoTest() {
UserInfo userInfo = initUserInfo();
when(userInfoService.insert(any())).thenReturn(1);
logger.info("++++++++++++++++++++++++++" + userInfo.toString());
// 调用接口,传入添加的用户参数
try{
String response = mockMvc.perform(post("/userInfo/add").contentType(MediaType.APPLICATION_JSON)
.content(userInfo.toString()).header("SESSIONNO", "EA60F3C2C7384DBA8A7B8B114474DC12"))
.andReturn().getResponse().getContentAsString();
logger.info("******************" + response); }catch (Exception e) {
e.printStackTrace();
} } @Test
public void addTest() {
try {
// 1. controller mvc test
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/userInfo/add"))
.andExpect(MockMvcResultMatchers.handler().handlerType(UserInfoController.class))
.andExpect(MockMvcResultMatchers.handler().methodName("addUserInfo"))
// .andExpect(MockMvcResultMatchers.view().name("demo/hello"))
// .andExpect(MockMvcResultMatchers.model().attributeExists("msg"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print())
.andReturn();
// Assert.assertNotNull(result.getModelAndView().getModel().get("msg")); }catch (Exception e) {
e.printStackTrace();
}
} /**
* 模拟update测试
*/
@Test
public void updateUserInfo() {
try{
// String response = mockMvc.perform(post("/user/updateUser").contentType(MediaType.APPLICATION_JSON)
// .content(userInfo.toString()).header("SESSIONNO", "EA60F3C2C7384DBA8A7B8B114474DC12"))
// .andReturn().getResponse().getContentAsString();
// logger.info("update****" + response);
}catch (Exception e) {
e.printStackTrace();
}
} private UserInfo initUserInfo() {
UserInfo userInfo = new UserInfo();
userInfo.setBirthday(new Timestamp(System.currentTimeMillis()));
userInfo.setCreateTime(new Timestamp(System.currentTimeMillis()));
userInfo.setEducation(5);
userInfo.setIdCardCode("********************");
userInfo.setMaritalStatus(1);
userInfo.setNickName("社会主义接班人");
userInfo.setPassword(encoderByMd5("a123456"));
userInfo.setPhoneNumber("************");
userInfo.setSex(1);
userInfo.setStatus(1);
userInfo.setUserAddress("hlxj");
userInfo.setUserEmail("**********@qq.com");
userInfo.setUserImage("图片");
userInfo.setUserName("dsc"); return userInfo;
} private String encoderByMd5(String password) {
//确定计算方法
String md5Password = null;
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
BASE64Encoder base64en = new BASE64Encoder();
//加密后的字符串
md5Password = base64en.encode(md5.digest(password.getBytes("utf-8")));
logger.info(md5Password);
}catch (Exception e){
e.printStackTrace();
} return md5Password;
}
}

  第二种模拟web请求

  

@RunWith(SpringRunner.class)
public class ServiceTest { private static final Logger logger = LogManager.getLogger(ServiceTest.class); @InjectMocks
UserInfoController userInfoController; @Mock
UserInfoService userInfoService; @Before
public void init() {
UserInfo userInfo = initUserInfo(); given(userInfoService.insert(any())).willReturn(1);
given(userInfoService.selectUnique(any())).willReturn(null, userInfo); } @Test
public void testAdd() {
UserInfo userInfo = new UserInfo();
userInfoController.addUserInfo(userInfo);
userInfo = initUserInfo();
userInfoController.addUserInfo(userInfo); } @Test
public void getUserInfoTest() {
UserInfo userInfo = new UserInfo();
logger.info("测试1*** " + userInfoController.getUserInfo(userInfo));
userInfo.setId(3L);
logger.info("测试2*** " + userInfoController.getUserInfo(userInfo));
} private UserInfo initUserInfo() {
UserInfo userInfo = new UserInfo();
userInfo.setBirthday(new Timestamp(System.currentTimeMillis()));
userInfo.setCreateTime(new Timestamp(System.currentTimeMillis()));
userInfo.setEducation(5);
userInfo.setIdCardCode("********************");
userInfo.setMaritalStatus(1);
userInfo.setNickName("社会主义接班人");
userInfo.setPassword(encoderByMd5("a123456"));
userInfo.setPhoneNumber("************");
userInfo.setSex(1);
userInfo.setStatus(1);
userInfo.setUserAddress("hlxj");
userInfo.setUserEmail("**********@qq.com");
userInfo.setUserImage("图片");
userInfo.setUserName("dsc"); return userInfo;
} private String encoderByMd5(String password) {
//确定计算方法
String md5Password = null;
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
BASE64Encoder base64en = new BASE64Encoder();
//加密后的字符串
md5Password = base64en.encode(md5.digest(password.getBytes("utf-8")));
logger.info(md5Password);
}catch (Exception e){
e.printStackTrace();
} return md5Password;
}
}

  以上两种只是我的个人测试,由于刚刚开始试验,对于一些细节还不是熟悉,期待日后修改。。。

Mockito单元测试实战的更多相关文章

  1. SpringBootTest单元测试实战、SpringBoot测试进阶高级篇之MockMvc讲解

    1.@SpringBootTest单元测试实战 简介:讲解SpringBoot的单元测试 1.引入相关依赖 <!--springboot程序测试依赖,如果是自动创建项目默认添加--> &l ...

  2. 小D课堂 - 零基础入门SpringBoot2.X到实战_第4节 Springboot2.0单元测试进阶实战和自定义异常处理_17、SpringBootTest单元测试实战

    笔记 1.@SpringBootTest单元测试实战     简介:讲解SpringBoot的单元测试         1.引入相关依赖              <!--springboot程 ...

  3. JUnit + Mockito 单元测试

    原 JUnit + Mockito 单元测试(二) 2015年01月05日 17:26:02 sp42a 阅读数:60755 版权声明:本文为博主原创文章,未经博主允许不得转载. https://bl ...

  4. JUnit + Mockito 单元测试(二)

    摘自: http://blog.csdn.net/zhangxin09/article/details/42422643 版权声明:本文为博主原创文章,未经博主允许不得转载. 目录(?)[-] 入门 ...

  5. 使用 Mockito 单元测试 – 教程

    tanyuanji@126.com 版本历史 - - - - 使用 Mockito 进行测试 该教程主要讲解 Mockito 框架在Eclipse IDE 中的使用   目录 tanyuanji@12 ...

  6. JUnit + Mockito 单元测试(二)(good)

    import org.junit.Test; import org.mockito.Matchers; import org.mockito.Mockito; import java.util.Lis ...

  7. Mockito单元测试

    Mockito简介 Mockito是一个单元测试框架,需要Junit的支持.在我们的项目中,都存在相当多的依赖关系,当我们在测试某一个业务相关的接口或则方法时,绝大多数时候是没有办法或则很难去添加所有 ...

  8. 基于spring与mockito单元测试Mock对象注入

    转载:http://www.blogjava.net/qileilove/archive/2014/03/07/410713.html 1.关键词 单元测试.spring.mockito 2.概述 单 ...

  9. 一文让你快速上手 Mockito 单元测试框架

    前言 在计算机编程中,单元测试是一种软件测试方法,通过该方法可以测试源代码的各个单元功能是否适合使用.为代码编写单元测试有很多好处,包括可以及早的发现代码错误,促进更改,简化集成,方便代码重构以及许多 ...

随机推荐

  1. 038_nginx backlog配置

    一. backlog=number sets the backlog parameter in the listen() call that limits the maximum length for ...

  2. OpenCV使用中的一些总结

    一.threshold阈值操作 1.阈值可以被视作最简单的图像分割方法.例如,从一副图像中利用阈值分割出我们需要的物体部分,这样的图像分割方法基于图像中的物体与背景之间的灰度差异. 2.thresho ...

  3. 【原创】大叔经验分享(1)在yarn上查看hive完整执行sql

    hive执行sql提交到yarn上的任务名字是被处理过的,通常只能显示sql的前边一段和最后几个字符,这样就会带来一些问题: 1)相近时间提交了几个相近的sql,相互之间无法区分: 2)一个任务有问题 ...

  4. Python-Django 模型层-多表查询-2

    -related_name:基于双下划线的跨表查询,修改反向查询的字段 -related_query_name:基于对象的跨表查询,修改反向查询字段 publish = ForeignKey(Blog ...

  5. 解决爬虫中遇到的js加密问题之有道登录js逆向解析

    具体实现在github上面(有详细的步骤): https://github.com/WYL-BruceLong/Spider_JS_ReverseParsin

  6. Hdu 1022 Train Problem I 栈

    Train Problem I Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) ...

  7. main函数中System.exit()的作用

    main()主函数再熟悉不过,了解java的人也都知道System.exit()方法是停止虚拟机运行.那这里为什么还要单独写一篇博客,都是源于朋友发的一张最近刚买的T恤照片,就是上面这张图.这是一个经 ...

  8. js分析 快速定位 js 代码, 还原被混淆压缩的 js 代码

    -1.目录 0.参考 1.页面表现 2. 慢镜头观察:低速网络请求 3. 从头到尾调试:Fiddler 拦截 index.html 并添加 debugger; 4. 快速定位 js 代码 5. 还原被 ...

  9. 01.pandas

    01.Series # -*- coding: utf-8 -*- """ Series 객체 특징 - pandas 제공 1차원 자료구성 - DataFrame 칼 ...

  10. Python学习(四十一)—— Djago进阶

    一.分页 Django的分页器(paginator) view from django.shortcuts import render,HttpResponse # Create your views ...