mockito详解二

来源:互联网 发布:淘宝照片处理教程 编辑:程序博客网 时间:2024/06/18 15:38

接着来:

  • @Mock 注解
   public class ArticleManagerTest {       @Mock private ArticleCalculator calculator;       @Mock private ArticleDatabase database;       @Mock private UserProvider userProvider;       private ArticleManager manager; 重要的是你需要在一些基类或者测试用例中调用 MockitoAnnotations.initMocks(testClass);

. 链式的编写风格

 when(mock.someMethod("some arg"))   .thenThrow(new RuntimeException())   .thenReturn("foo"); //First call: throws runtime exception: mock.someMethod("some arg"); //Second call: prints "foo" System.out.println(mock.someMethod("some arg")); //Any consecutive call: prints "foo" as well (last stubbing wins). System.out.println(mock.someMethod("some arg"));//当然你也可以这么写 when(mock.someMethod("some arg"))   .thenReturn("one", "two", "three");
  • 使用thenReturn,thenThrow我们已经足够覆盖一些简单的测试了,如果你需要一些callback的测试,下面试例子
 when(mock.someMethod(anyString())).thenAnswer(new Answer() {     Object answer(InvocationOnMock invocation) {         Object[] args = invocation.getArguments();         Object mock = invocation.getMock();         return "called with arguments: " + args;     } }); //the following prints "called with arguments: foo" System.out.println(mock.someMethod("foo"));
  • 对于空的返回方法需要一个不同的when(object),因为编译的时候不喜欢空的方法在用例中
   doThrow(new RuntimeException()).when(mockedList).clear();   //following throws RuntimeException:   mockedList.clear();doReturn(Object)doThrow(Throwable...)doThrow(Class)doAnswer(Answer)doNothing()doCallRealMethod()

stub 空的方法
stub 在spy 对象中的方法(见下文)

  • spy对象
 List list = new LinkedList();   List spy = spy(list);   //optionally, you can stub out some methods:   when(spy.size()).thenReturn(100);   //using the spy calls *real* methods   spy.add("one");   spy.add("two");   //prints "one" - the first element of a list   System.out.println(spy.get(0));   //size() method was stubbed - 100 is printed   System.out.println(spy.size());   //optionally, you can verify   verify(spy).add("one");   verify(spy).add("two");

重要提示,有时候我们在stubbing spies用when(object)我们需要使用doReturn|Answer|Throw() stubbing中的一些成员方法,例如

  List list = new LinkedList();   List spy = spy(list);   //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)   when(spy.get(0)).thenReturn("foo");   //You have to use doReturn() for stubbing   doReturn("foo").when(spy).get(0);
  • 你可以为一个模拟创建指定的返回值与指定的策略(since 1.7)
  Foo mock = mock(Foo.class, Mockito.RETURNS_SMART_NULLS);   Foo mockTwo = mock(Foo.class, new YourOwnAnswer());

public static final Answer RETURNS_SMART_NULLS

  • 真正的部分mock(since 1.8)
 //you can create partial mock with spy() method:    List list = spy(new LinkedList());    //you can enable partial mock capabilities selectively on mocks:    Foo mock = mock(Foo.class);    //Be sure the real implementation is 'safe'.    //If real implementation throws exceptions or depends on specific state of the object then you're in trouble.    when(mock.someMethod()).thenCallRealMethod();
  • mock的重置
  List mock = mock(List.class);   when(mock.size()).thenReturn(10);   mock.add(1);   reset(mock);   //at this point the mock forgot any interactions & stubbing

不要自我伤害,reset()在一个测试方法中有一点坏代码的味道,你有可能因此测试更多

  • 行为驱动开发的别名(since 1.8)
    BDD的测试风格,当前的subbing api when用法并没有given when then风格的语法明确。
 import static org.mockito.BDDMockito.*; Seller seller = mock(Seller.class); Shop shop = new Shop(seller); public void shouldBuyBread() throws Exception {   //given   given(seller.askForBread()).willReturn(new Bread());   //when   Goods goods = shop.buyBread();   //then   assertThat(goods, containBread()); }

shop对象调用buybread的时候,改方法调用了seller里面的askForBread()方法,返回new Bread(),最后assertThat比较两个对象


  • 序列化的mock(since 1.8.1)
    在新的特性中加入了序列化的mock,


List serializableMock = mock(List.class, withSettings().serializable());
用BBD风格的序列化的部分mock
 List<Object> list = new ArrayList<Object>(); List<Object> spy = mock(ArrayList.class, withSettings()                 .spiedInstance(list)                 .defaultAnswer(CALLS_REAL_METHODS)                 .serializable());
0 0
原创粉丝点击