java – 如何在调用模拟对象的方法时验证返回值

使用Mockito,有没有办法对一个对象进行spy()并验证一个对象是否被指定的#s次调用给定的#并且它返回这些调用的期望值?

我想做类似以下的事情:

class HatesTwos {
  boolean hates(int val) {
    return val == 2;
  }
}

HatesTwos hater = spy(new HatesTwos());
hater.hates(1);
assertFalse(verify(hater, times(1)).hates(1));

reset(hater);
hater.hates(2);
assertTrue(verify(hater, times(1)).hates(2));

解决方法:

您可以使用Answer界面捕获真实的响应.

public class ResultCaptor<T> implements Answer {
    private T result = null;
    public T getResult() {
        return result;
    }

    @Override
    public T answer(InvocationOnMock invocationOnMock) throws Throwable {
        result = (T) invocationOnMock.callRealMethod();
        return result;
    }
}

预期用途:

class HatesTwos {
    boolean hates(int val) {
        return val == 2;
    }
}

HatesTwos hater = spy(new HatesTwos());

// let's capture the return values from hater.hates(int)
ResultCaptor<Boolean> hateResultCaptor = new ResultCaptor<>();
doAnswer(hateResultCaptor).when(hater).hates(anyInt());

hater.hates(1);
verify(hater, times(1)).hates(1);
assertFalse(hateResultCaptor.getResult());

reset(hater);

hater.hates(2);
verify(hater, times(1)).hates(2);
assertTrue(hateResultCaptor.getResult());
上一篇:使用P6Spy监控你的SQL输出


下一篇:【转载】 利用p6spy拦截并查看数据库执行操作