0%

Mockito浅谈

Mockito浅谈


Mockito简介

  • 什么是mock?
    在软件开发的世界之外, “mock”一词是指模仿或者效仿。 因此可以将“mock”理解为一个替身,替代者. 在软件开发中提及”mock”,通常理解为模拟对象或者Fake。

  • 为什么需要Mock?
    Mock是为了解决units之间由于耦合而难于被测试的问题。所以mock object是unit test的一部分。

Mock的好处是什么?

  • 提前创建测试,TDD(测试驱动开发)

    这是个最大的好处吧。如果你创建了一个Mock那么你就可以在service接口创建之前写Service Tests了,这样你就能在开发过程中把测试添加到你的自动化测试环境中了。换句话说,模拟使你能够使用测试驱动开发。

  • 团队可以并行工作

    这类似于上面的那点;为不存在的代码创建测试。但前面讲的是开发人员编写测试程序,这里说的是测试团队来创建。当还没有任何东西要测的时候测试团队如何来创建测试呢?模拟并针对模拟测试!这意味着当service借口需要测试时,实际上QA团队已经有了一套完整的测试组件;没有出现一个团队等待另一个团队完成的情况。这使得模拟的效益型尤为突出了。

  • 你可以创建一个验证或者演示程序。

    由于Mocks非常高效,Mocks可以用来创建一个概念证明,作为一个示意图,或者作为一个你正考虑构建项目的演示程序。这为你决定项目接下来是否要进行提供了有力的基础,但最重要的还是提供了实际的设计决策。

  • 为无法访问的资源编写测试

    这个好处不属于实际效益的一种,而是作为一个必要时的“救生圈”。有没有遇到这样的情况?当你想要测试一个service接口,但service需要经过防火墙访问,防火墙不能为你打开或者你需要认证才能访问。遇到这样情况时,你可以在你能访问的地方使用MockService替代,这就是一个“救生圈”功能。

  • Mock 可以交给用户

    在有些情况下,某种原因你需要允许一些外部来源访问你的测试系统,像合作伙伴或者客户。这些原因导致别人也可以访问你的敏感信息,而你或许只是想允许访问部分测试环境。在这种情况下,如何向合作伙伴或者客户提供一个测试系统来开发或者做测试呢?最简单的就是提供一个mock,无论是来自于你的网络或者客户的网络。soapUI mock非常容易配置,他可以运行在soapUI或者作为一个war包发布到你的java服务器里面。

  • 隔离系统

    有时,你希望在没有系统其他部分的影响下测试系统单独的一部分。由于其他系统部分会给测试数据造成干扰,影响根据数据收集得到的测试结论。使用mock你可以移除掉除了需要测试部分的系统依赖的模拟。当隔离这些mocks后,mocks就变得非常简单可靠,快速可预见。这为你提供了一个移除了随机行为,有重复模式并且可以监控特殊系统的测试环境。

Mockito使用示例

模拟对象

1
// 模拟LinkedList 的一个对象  
2
LinkedList mockedList = mock(LinkedList.class);
3
// 此时调用get方法,会返回null,因为还没有对方法调用的返回值做模拟
4
System.out.println(mockedList.get(0));

模拟方法调用的返回值

1
// 模拟获取第一个元素时,返回字符串first。  给特定的方法调用返回固定值在官方说法中称为stub。
2
when(mockedList.get(0)).thenReturn("first");
3
// 此时打印输出first
4
System.out.println(mockedList.get(0));

模拟方法调用抛出异常

1
// 模拟获取第二个元素时,抛出RuntimeException  
2
when(mockedList.get(1)).thenThrow(new RuntimeException());
3
// 此时将会抛出RuntimeException  
4
System.out.println(mockedList.get(1));

如果一个函数没有返回值类型,那么可以使用此方法模拟异常抛出

1
doThrow(new RuntimeException("clear exception")).when(mockedList).clear();
2
mockedList.clear();

模拟调用方法时的参数匹配

1
// anyInt()匹配任何int参数,这意味着参数为任意值,其返回值均是element  
2
when(mockedList.get(anyInt())).thenReturn("element");
3
// 此时打印是element
4
System.out.println(mockedList.get(999));

模拟方法调用次数

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

校验行为

1
// mock creation
2
List mockedList = mock(List.class);
3
// using mock object
4
mockedList.add("one");
5
mockedList.clear();
6
//verification
7
verify(mockedList).add("one");
8
verify(mockedList).clear();

模拟方法调用(Stubbing)

1
//You can mock concrete classes, not just interfaces
2
LinkedList mockedList = mock(LinkedList.class);
3
//stubbing
4
when(mockedList.get(0)).thenReturn("first");
5
when(mockedList.get(1)).thenThrow(new RuntimeException());
6
//following prints "first"
7
System.out.println(mockedList.get(0));
8
//following throws runtime exception
9
System.out.println(mockedList.get(1));
10
//following prints "null" because get(999) was not stubbed
11
System.out.println(mockedList.get(999));
12
13
verify(mockedList).get(0);

参数匹配

1
//stubbing using built-in anyInt() argument matcher
2
when(mockedList.get(anyInt())).thenReturn("element");
3
//stubbing using custom matcher (let's say isValid() returns your own matcher implementation):
4
when(mockedList.contains(argThat(isValid()))).thenReturn("element");
5
//following prints "element"
6
System.out.println(mockedList.get(999));
7
//you can also verify using an argument matcher
8
verify(mockedList).get(anyInt());
9
//argument matchers can also be written as Java 8 Lambdas
10
verify(mockedList).add(someString -> someString.length() > 5);

校验方法调用次数

1
//using mock
2
mockedList.add("once");
3
4
mockedList.add("twice");
5
mockedList.add("twice");
6
7
mockedList.add("three times");
8
mockedList.add("three times");
9
mockedList.add("three times");
10
//following two verifications work exactly the same - times(1) is used by default
11
verify(mockedList).add("once");
12
verify(mockedList, times(1)).add("once");
13
//exact number of invocations verification
14
verify(mockedList, times(2)).add("twice");
15
verify(mockedList, times(3)).add("three times");
16
//verification using never(). never() is an alias to times(0)
17
verify(mockedList, never()).add("never happened");
18
//verification using atLeast()/atMost()
19
verify(mockedList, atLeastOnce()).add("three times");
20
verify(mockedList, atLeast(2)).add("five times");
21
verify(mockedList, atMost(5)).add("three times");

模拟无返回方法抛出异常

1
doThrow(new RuntimeException()).when(mockedList).clear();
2
//following throws RuntimeException:
3
mockedList.clear();

校验方法调用顺序

1
// A. Single mock whose methods must be invoked in a particular order
2
List singleMock = mock(List.class);
3
//using a single mock
4
singleMock.add("was added first");
5
singleMock.add("was added second");
6
//create an inOrder verifier for a single mock
7
InOrder inOrder = inOrder(singleMock);
8
//following will make sure that add is first called with "was added first, then with "was added second"
9
inOrder.verify(singleMock).add("was added first");
10
inOrder.verify(singleMock).add("was added second");
11
12
// B. Multiple mocks that must be used in a particular order
13
List firstMock = mock(List.class);
14
List secondMock = mock(List.class);
15
//using mocks
16
firstMock.add("was called first");
17
secondMock.add("was called second");
18
//create inOrder object passing any mocks that need to be verified in order
19
InOrder inOrder = inOrder(firstMock, secondMock);
20
//following will make sure that firstMock was called before secondMock
21
inOrder.verify(firstMock).add("was called first");
22
inOrder.verify(secondMock).add("was called second");
23
// Oh, and A + B can be mixed together at will

校验方法是否从未调用

1
//using mocks - only mockOne is interacted
2
mockOne.add("one");
3
//ordinary verification
4
verify(mockOne).add("one");
5
//verify that method was never called on a mock
6
verify(mockOne, never()).add("two");
7
//verify that other mocks were not interacted
8
verifyZeroInteractions(mockTwo, mockThree);

快速创建Mock对象

1
public class ArticleManagerTest {
2
   @Mock private ArticleCalculator calculator;
3
      @Mock private ArticleDatabase database;
4
      @Mock private UserProvider userProvider;
5
      @Before
6
      public void before(){
7
          MockitoAnnotations.initMocks(this);
8
      }
9
}

自定义返回不同结果

1
when(mock.someMethod("some arg"))
2
   .thenThrow(new RuntimeException())  // 第一次会抛出异常
3
   .thenReturn("foo"); // 第二次会返回这个结果
4
//First call: throws runtime exception:
5
mock.someMethod("some arg"); // 第一次
6
//Second call: prints "foo"
7
System.out.println(mock.someMethod("some arg")); // 第二次
8
//Any consecutive call: prints "foo" as well (last stubbing wins).
9
System.out.println(mock.someMethod("some arg")); // 第n次(n> 2),依旧以最后返回最后一个配置

对返回结果进行拦截

1
when(mock.someMethod(anyString())).thenAnswer(new Answer() {
2
    Object answer(InvocationOnMock invocation) {
3
        Object[] args = invocation.getArguments();
4
        Object mock = invocation.getMock();
5
        return "called with arguments: " + args;
6
    }
7
});
8
//the following prints "called with arguments: foo"
9
System.out.println(mock.someMethod("foo"));

Mock函数操作

可以通过doThrow(), doAnswer(), doNothing(), doReturn() and doCallRealMethod() 来自定义函数操作。

暗中调用真实对象

1
List list = new LinkedList();
2
List spy = spy(list);
3
//optionally, you can stub out some methods:
4
when(spy.size()).thenReturn(100);
5
//using the spy calls *real* methods
6
spy.add("one");
7
spy.add("two");
8
//prints "one" - the first element of a list
9
System.out.println(spy.get(0));
10
//size() method was stubbed - 100 is printed
11
System.out.println(spy.size());
12
//optionally, you can verify
13
verify(spy).add("one");
14
   verify(spy).add("two");

改变默认返回值

1
Foo mock = mock(Foo.class, Mockito.RETURNS_SMART_NULLS);
2
Foo mockTwo = mock(Foo.class, new YourOwnAnswer());

捕获函数的参数值

1
ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);
2
verify(mock).doSomething(argument.capture());
3
assertEquals("John", argument.getValue().getName());

部分Mock

1
//you can create partial mock with spy() method:
2
List list = spy(new LinkedList());
3
//you can enable partial mock capabilities selectively on mocks:
4
Foo mock = mock(Foo.class);
5
//Be sure the real implementation is 'safe'.
6
//If real implementation throws exceptions or depends on specific state of the object then you're in trouble.
7
when(mock.someMethod()).thenCallRealMethod();

重置Mock

1
List mock = mock(List.class);
2
when(mock.size()).thenReturn(10);
3
mock.add(1);
4
reset(mock);
5
//at this point the mock forgot any interactions & stubbing

序列化

1
List<Object> list = new ArrayList<Object>();
2
List<Object> spy = mock(ArrayList.class, withSettings()
3
                 .spiedInstance(list)
4
                 .defaultAnswer(CALLS_REAL_METHODS)
5
                 .serializable());

检查超时

1
//passes when someMethod() is called within given time span
2
verify(mock, timeout(100)).someMethod();
3
//above is an alias to:
4
verify(mock, timeout(100).times(1)).someMethod();
5
//passes when som`eMethod() is called *exactly* 2 times within given time span
6
verify(mock, timeout(100).times(2)).someMethod();
7
//passes when someMethod() is called *at least* 2 times within given time span
8
verify(mock, timeout(100).atLeast(2)).someMethod();
9
//verifies someMethod() within given time span using given verification mode
10
//useful only if you have your own custom verification modes.
11
verify(mock, new Timeout(100, yourOwnVerificationMode)).someMethod();

Mock详情

1
Mockito.mockingDetails(someObject).isMock();
2
Mockito.mockingDetails(someObject).isSpy();
坚持原创技术分享,您的支持将鼓励我继续创作!