ITeye博客

Mockito入门

Rocky_rup · 2008-12-17 18:35 · 学习备忘录 · Markdown

简介

 

InfoQ-使用Mockito 1.5监视普通对象 写道

Mockito是一个针对Java的mocking框架。它与EasyMock和jMock很相似,但是通过在执行后校验什么已经被调用,它消除了对期望行为(expectations)的需要。其它的mocking库需要你在执行前记录期望行为(expectations),而这导致了丑陋的初始化代码。

 

 更多信息请参考如下位置,

 原文链接:http://www.infoq.com/cn/news/2008/09/mockito-1.5

 官方网站:http://code.google.com/p/mockito/

 

入门

以下内容均参考至http://mockito.googlecode.com/svn/branches/1.6/javadoc/org/mockito/Mockito.html。

在任何应用Mockito的地方,加上如下片段:

import static org.mockito.Mockito.*;

 

模拟对象

// 模拟LinkedList 的对象
LinkedList mockedList = mock(LinkedList.class);

// 此时调用get方法,是会返回null,因为还没有对方法调用的返回值做模拟 
System.out.println(mockedList.get(999));

 

 模拟方法调用的返回值

 

// 模拟获取第一个元素时,返回字符串first
when(mockedList.get(0)).thenReturn("first");

// 此时打印输出first
System.out.println(mockedList.get(0));

 

模拟方法调用抛出异常

// 模拟获取第二个元素时,抛出RuntimeException
when(mockedList.get(1)).thenThrow(new RuntimeException());

// 此时将会抛出RuntimeException
System.out.println(mockedList.get(1));

 没有返回值类型的方法也可以模拟异常抛出:

doThrow(new RuntimeException()).when(mockedList).clear();

 

模拟方法调用的参数匹配

// anyInt()匹配任何int参数,这意味着参数为任意值,其返回值均是element
when(mockedList.get(anyInt())).thenReturn("element");

// 此时打印是element
System.out.println(mockedList.get(999));

 更灵活的参数匹配,请参见http://mockito.googlecode.com/svn/branches/1.6/javadoc/org/mockito/Matchers.html

验证方法调用次数

// 调用add一次
mockedList.add("once");

// 下面两个写法验证效果一样,均验证add方法是否被调用了一次
verify(mockedList).add("once");
verify(mockedList, times(1)).add("once");

 还可以通过atLeast(int i)和atMost(int i)来替代time(int i)来验证被调用的次数最小值和最大值。

 

收尾

上面仅列举了一些常用的,更多用法和技巧还请详细参考http://mockito.googlecode.com/svn/branches/1.6/javadoc/org/mockito/Mockito.html。让Mockito使测试驱动开发更有趣吧!

评论(1)

  1. #1 楼 · Norther · 2010-09-23 19:38

    实现方式让人一亮,很优雅,像自然语言一样,很不错!

评论功能维护中,当前仅展示历史评论。