我在使用Mockito验证对模拟方法的调用次数时遇到麻烦。
这是我的测试
@Mock
private SquareClient squareClient;
@Mock
private PaymentsApi paymentsApi;
@Test
public void testBlah() throws Exception {
...
when(squareClient.getPaymentsApi().getPayment("p1")).thenReturn(VALID_PAYMENT_RESPONSE);
sut.process(EXAMPLE_PAYLOAD);
verify(squareClient).getPaymentsApi().getPayment("p1"); //<--------------error here
}
这是我的设置方法
@Before
public void setup() {
...
when(squareClient.getPaymentsApi()).thenReturn(paymentsApi);
...
}
错误
想要1次:在com.squareup.square.SquareClient.getPaymentsApi(SquareClient.java:239)但是是2次:
看起来不错,但是当您看到两个电话打来时。 。 有人在服务中,
Payment payment = squareClient.getPaymentsApi().getPayment(paymentId).getPayment();
和测试中的一个。为什么这是这里?
when(squareClient.getPaymentsApi().getPayment("p1")).thenReturn(VALID_PAYMENT_RESPONSE);
我的问题
首先,应该只有1个电话。
其次,当我检查2次verify(squareClient, times(2)).getPayment("p1")
时,我得到一个空指针,因为getPaymentsApi()现在为空。这是因为模拟when()没有第二次应用吗?
直接将您的@Test中的when()语句应用于PaymentsApi对象。
when(paymentsApi.getPayment("p1")).thenReturn(VALID_PAYMENT_RESPONSE);
使用“ when()”时,不能链接方法调用。