Mockito Framework用法简介

编程过程可以抽象为expect-run-verify,而在Java中我们常用单元测试来保证程序运行结果符合我们的预期。

Mockito可以实现:

  • 在得到程序输出结果后,验证结果是否符合预期;
  • 在其依赖方法还没有编写完成时,mock接口的执行结果。

mock

  • 通过when(...).then(...)指定具体行为动作的mock结果;
  • 可通过如下方式自定义响应:
 when(mock.someMethod(anyString())).thenAnswer(
     new Answer() {
         public Object answer(InvocationOnMock invocation) {
             Object[] args = invocation.getArguments();
             Object mock = invocation.getMock();
             return "called with arguments: " + Arrays.toString(args);
         }
 });

 //Following prints "called with arguments: [foo]"
 System.out.println(mock.someMethod("foo"));
import static org.mockito.Mockito.*;

// 通过mock方法创建一个mock类,该实例的所有调用返回的都是mock值
List mockedList = mock(List.class);

// 使用mock实例,不会抛出任何非检查型异常
mockedList.add("one");
mockedList.clear();

// 验证某方法是否执行过
verify(mockedList).add("one");
verify(mockedList).clear();

//定义一个stub存根,mock方法执行返回结果
when(mockedList.get(0)).thenReturn("first");

// 命中stub,符合上面定义的mock条件,返回mock结果
System.out.println(mockedList.get(0));

// 因为get(999)未命中stub,故返回null
System.out.println(mockedList.get(999));

测试输出结果如下:

Mockito Framework用法简介_第1张图片
mock测试结果

@mock

public class ArticleManagerTest extends SampleBaseTestCase {

       @Mock private ArticleCalculator calculator;
       @Mock(name = "database") private ArticleDatabase dbMock;
       @Mock(answer = RETURNS_MOCKS) private UserProvider userProvider;
       @Mock(extraInterfaces = {Queue.class, Observer.class}) private  articleMonitor;

       private ArticleManager manager;

       @Before public void setup() {
           manager = new ArticleManager(userProvider, database, calculator, articleMonitor);
       }
   }

   public class SampleBaseTestCase {

       @Before public void initMocks() {
            //MockitoAnnotations.initMocks(this)必须在test执行前调用
           MockitoAnnotations.initMocks(this);
       }
   }

spy

  • mock代理部分指定的方法,其余方法都执行真实的方法动作。
List list = new LinkedList();
List spy = spy(list);

//可以选择性stub部分方法,其余未被代理的方法会真实执行
when(spy.size()).thenReturn(100);

//真实调用执行
spy.add("one");
spy.add("two");

//打印第一个元素
System.out.println(spy.get(0));

//size() 方法被mock代理了,返回设定值:100
System.out.println(spy.size());

//验证
verify(spy).add("one");
verify(spy).add("two");

测试输出结果如下:


Mockito Framework用法简介_第2张图片
spy测试结果

@spy

public class Test{
   //Instance for spying is created by calling constructor explicitly:
   @Spy Foo spyOnFoo = new Foo("argument");
   //Instance for spying is created by mockito via reflection (only default constructors supported):
   @Spy Bar spyOnBar;
   @Before
   public void init(){
      MockitoAnnotations.initMocks(this);
   }
   ...
}

/****************等同于*********/
Foo spyOnFoo = Mockito.spy(new Foo("argument"));
Bar spyOnBar = Mockito.spy(new Bar());

verify

  • 验证执行方法是否被调用执行指定的次数
List mockedList = mock(List.class);
//using mock
 mockedList.add("once");

 mockedList.add("twice");
 mockedList.add("twice");

 mockedList.add("three times");
 mockedList.add("three times");
 mockedList.add("three times");

 //following two verifications work exactly the same - times(1) is used by default
 verify(mockedList).add("once");
 verify(mockedList, times(1)).add("once");

 //exact number of invocations verification
 verify(mockedList, times(2)).add("twice");
 verify(mockedList, times(3)).add("three times");

 //verification using never(). never() is an alias to times(0)
 verify(mockedList, never()).add("never happened");

 //verification using atLeast()/atMost()
 verify(mockedList, atLeastOnce()).add("three times");
 verify(mockedList, atLeast(2)).add("three times");
 verify(mockedList, atMost(5)).add("three times");

你可能感兴趣的:(Mockito Framework用法简介)