Mockito Hello World

项目配置

  IDE是Intellij IDEA,用gradle配置项目.
  新建一个Java项目,gradle中需要有这个:
 
repositories { jcenter() }
dependencies { testCompile "org.mockito:mockito-core:1.+" }
单元测试用JUnit 4,所以gradle文件如下:
apply plugin: 'java'
apply plugin: 'idea' sourceCompatibility = 1.5
version = '1.0' repositories {
mavenCentral()
jcenter()
} dependencies {
testCompile group: 'junit', name: 'junit', version: '4.11'
testCompile "org.mockito:mockito-core:1.8.5"
}

  写好之后在命令行执行:gradle idea
  相关的包就会下载好,并出现在这里:
 
 

Hello World程序

  想着写一个Hello World说明一下Mockito怎么用,结果写着写着就写复杂了.
  先看代码:
package com.mengdd.examples.mockito;

public class HelloWorld {
private MyRobot mRobot; public MyRobot getRobot() {
return mRobot;
} public void setRobot(MyRobot robot) {
this.mRobot = robot;
} /**
* This is the method we want to test.
* When there is an robot, this method return the robot's information
* otherwise, return some sorry text
*/
public String sayHello() {
MyRobot robot = getRobot();
if (null != robot) {
return robot.getSomeInfo();
} return "No robot here, sorry!";
} /**
* MyRobot class
*/
public static class MyRobot { /**
* Get some information from somewhere, the implementation may varies
*/
public String getSomeInfo() {
return "Hello World -- From robot";
}
}
}

  这段代码里面包含了一个HelloWorld类和一个内部静态类MyRobot(我的机器人).
  HelloWorld中有一个方法叫sayHello(),是我们要测的方法.
  它会判断成员变量是否为空,不为空则调用其方法获取一些信息,否则返回一条提示信息.
 
 
  -------------------
  这里插播一下,关于内部类的介绍可以参见以前的一篇笔记:http://www.cnblogs.com/mengdd/archive/2013/02/08/2909307.html
  内部静态类和内部非静态类可以类比:静态成员变量和非静态成员变量.
  -------------------
 
 
  测试类代码如下:
package com.mengdd.examples.mockito;

import org.junit.Test;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; public class HelloWorldTest {
@Test
public void testSayHelloWhenThereIsRobot() throws Exception {
// We want to test the sayHello() method in the class HelloWorld.
// But we don't care about how MyRobot get its information.(We can treat it as external interface). // Maybe the robot rely on many complicated things.(Although it's simple in this case.)
// And when the robot's actions change in the future, we don't need to change this test case. // We can mock the MyRobot's action to make it simple and just test whether sayHello() can do its own work. // Mock steps
HelloWorld.MyRobot robot = mock(HelloWorld.MyRobot.class); // Mock MyRobot class
String mockInfo = "some mock info";
when(robot.getSomeInfo()).thenReturn(mockInfo); // Set behavior for mock object // real object
HelloWorld helloWorld = new HelloWorld();//This is the real objec we want to test
helloWorld.setRobot(robot);//set the mock robot to real object // execute the target method we want to test
String result = helloWorld.sayHello(); // assert the result is what we want to have
assertThat(result, is(mockInfo));
}
}

  因为我们要测试的是HelloWorld的sayHello()方法是否能正常工作.
  我们需要假定其中robot的行为是正常的(我们并不关心robot实际上做的工作,以及它怎么做),所以这里用到了mock.
  比如如果机器人的实现中要发送一个请求,我们这里就是直接mock它得到的结果,而不是真的去发这个请求.
 
  就好像准备好了所需要的所有外部条件,看sayHello()方法的表现是否能符合我们的预期.
 
 
  为了全面起见,测试了sayHello()的另一种case,这里没有用到mockito.
@Test
public void testSayHelloWhenThereIsNoRobot() throws Exception {
HelloWorld helloWorld = new HelloWorld();
helloWorld.setRobot(null); String result = helloWorld.sayHello(); assertThat(result, is("No robot here, sorry!"));
}
 
 

参考资料

  官网: http://mockito.org/
  Mockito at github: https://github.com/mockito/mockito
  可以在这里看版本号: http://mvnrepository.com/artifact/org.mockito/
 

Mockito Hello World的更多相关文章

  1. Junit mockito 测试Controller层方法有Pageable异常

    1.问题 在使用MockMVC+Mockito模拟Service层返回的时候,当我们在Controller层中参数方法调用有Pageable对象的时候,我们会发现,我们没办法生成一个Pageable的 ...

  2. Junit mockito解耦合测试

    Mock测试是单元测试的重要方法之一. 1.相关网址 官网:http://mockito.org/ 项目源码:https://github.com/mockito/mockito api:http:/ ...

  3. Android 单元测试(junit、mockito、robolectric)

    1.运用JUnit4 进行单元测试 首先在工程的 src 文件夹内创建 test 和 test/java 文件夹. 打开工程的 build.gradle(Module:app)文件,添加JUnit4依 ...

  4. mockito使用心得

    前提:pom引用<dependency> <groupId>junit</groupId> <artifactId>junit</artifact ...

  5. Mock之easymock, powermock, and mockito

    easymock, powermock, and mockito Easymock Class Mocking Limitations To be coherent with interface mo ...

  6. 用Mockito mock普通的方法

    上面的例子是很理想化的状态,但是在实际的开发中,我们需要经常调用一些依赖特定环境的函数或者调用同事写的代码,而同事仅提供了接口.这个时候就需要利用Mockito来协助我们完成测试. 当然,你可以选择e ...

  7. mock测试框架Mockito

    无论是敏捷开发.持续交付,还是测试驱动开发(TDD)都把单元测试作为实现的基石.随着这些先进的编程开发模式日益深入人心,单元测试如今显得越来越重要了.在敏捷开发.持续交付中要求单元测试一定要快(不能访 ...

  8. Mockito自定义verify参数Matcher

    在TDD开发中,也许我们会遇见对一些重要的无返回值的行为测试,比如在用户的积分DB中增加用户的积分,这个行为对于我们的业务具有重要的价值,所以我们也希望能测试覆盖这部分业务价值.这个时候我们就得使用m ...

  9. Mockito学习资料

    官网:http://mockito.org/ https://dzone.com/refcardz/mockito

随机推荐

  1. IOS开发资料汇总

    1 IOS账号注册.程序发布流程 1)http://jamesli.cn/blog/?p=955 2)http://jamesli.cn/blog/?p=966 3)http://jamesli.cn ...

  2. NFS Volume Provider(Part II) - 每天5分钟玩转 OpenStack(63)

    上一节我们将 NFS volume provider 配置就绪,本节将创建 volume. 创建 volume 创建 NFS volume 操作方法与 LVM volume 一样,唯一区别是在 vol ...

  3. 通过监控线程状态来保证socket服务器的稳定运行

    云平台中使用的socket服务器是我们自己定义一套通信协议,并通过C#实现的一个socket服务. 该服务目前是和web服务一起运行在IIS容器中,通过启动一个永不退出的新线程来监听端口. 在开发的初 ...

  4. MySQL Range Optimization

    8.2.1.3 Range Optimization MYSQL的Range Optimization的目的还是尽可能的使用索引 The range access method uses a sing ...

  5. 构建自己的PHP框架--构建缓存组件(2)

    上一篇博客中使用文件实现了缓存组件,这一篇我们就使用Redis来实现一下,剩下的如何使用memcache.mysql等去实现缓存我就不一一去做了. 首先我们需要安装一下 redis 和 phpredi ...

  6. iOS 使用EZAudio库生成wav出错的情况

    使用EZAudio库 录M4A格式可以参考该库例子中的代码. 录wav格式得改下源码.看下面的代码 AVAudioSession *session = [AVAudioSession sharedIn ...

  7. 把《c++ primer》读薄(4-1 c和c++数组)

    督促读书,总结精华,提炼笔记,抛砖引玉,有不合适的地方,欢迎留言指正. c和c++的数组和指针都属于低级的复合数据类型,比如c++的数组,类似vector容器,指针类似迭代器.低级的数据类型优势是速度 ...

  8. 打造Orm经典,创CRUD新时代,Orm的反攻战

    让我们开启数据库无Linq.零sql时代(续) 第一部分 MQL qq群:225656797 demo下载: 点此下载(既然下载,就支持该文,关注我的博客) Moon.Orm 5.0 (MQL版) 版 ...

  9. 通过Redux源码学习基础概念一:简单例子入门

    最近公司有个项目使用react+redux来做前端部分的实现,正好有机会学习一下redux,也和小伙伴们分享一下学习的经验. 首先声明一下,这篇文章讲的是Redux的基本概念和实现,不包括react- ...

  10. TeamCity : 安装 Server

    本文介绍在 Ubuntu Server 14.04 中安装 TeamCity Server 10.0.1.Ubuntu Server 上已经创建了用户  tcuser.TeamCity 的安装包为 T ...