Mockito做单元测试时一些高级用法

在Mockito中,我们一般这样验证桩的调用:

Mockito.verify(xxx, Mockito.times(1)).func1(Mockito.anyObject());

但是有时候,我们希望能验证调用的基础上,再验证这个参数,可以这么搞:

ArgumentCaptor<TypeA> typeACaptor = ArgumentCaptor.forClass(TypeA.class);
Mockito.verify(xxx, Mockito.times(1)).fun1(typeACaptor.capture());

Assert.assertThat(typeACaptor.getValue().xxx(), is(yyy));

也可以

Mockito.verift(mock).mymethod(argThat(matcher));

matcher = new ArgumentMatcher<Collection<Integer>>() {
        @Override
        public boolean matches(Object o) {
            if (!(o instanceof Collection)) {
                return false;
            }
            Collection<Integer> coll = (Collection<Integer>) o;
            if (coll.size() != 2) {
                return false;
            }
            return coll.contains(10) && coll.contains(11);
        }
    }

如何只mock部分方法,可以用

Mockito.spy(XXX.class)

如何在Mockito.when时根据不同参数返回不同结果

when(mockObject.myMethod(anyString())).thenAnswer(
            new Answer<String>(){
            @Override
            public String answer(InvocationOnMock invocation){
                if ("value".equals(theProperty)){
                    return "result";
                }
                else if("otherValue".equals(theProperty)) {
                    return "otherResult";
                }
                return theProperty;
            }});

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *