[英]Why does mockito think my service is being called twice?
I'm having trouble using mockito to verify the number of calls to a mocked method.我在使用 mockito 来验证对模拟方法的调用次数时遇到问题。
This is my test这是我的测试
@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
}
This is my setup method这是我的设置方法
@Before
public void setup() {
...
when(squareClient.getPaymentsApi()).thenReturn(paymentsApi);
...
}
Error错误
Wanted 1 time: at com.squareup.square.SquareClient.getPaymentsApi(SquareClient.java:239) But was 2 times:
想要 1 次:在 com.squareup.square.SquareClient.getPaymentsApi(SquareClient.java:239) 但是是 2 次:
That's seems fine, but when you see the two calls come from.这看起来不错,但是当您看到两个调用来自。 .
. one is in the service ,
一个是在服务中,
Payment payment = squareClient.getPaymentsApi().getPayment(paymentId).getPayment();
And one in the test .和一个在测试中。 Why is this one here?
为什么会在这里?
when(squareClient.getPaymentsApi().getPayment("p1")).thenReturn(VALID_PAYMENT_RESPONSE);
My issues我的问题
Firstly, there should only be 1 call.首先,应该只有 1 个调用。
Secondly, when I check for 2 times verify(squareClient, times(2)).getPayment("p1")
I get a null pointer because getPaymentsApi() is now null.其次,当我检查 2 次
verify(squareClient, times(2)).getPayment("p1")
我得到一个空指针,因为 getPaymentsApi() 现在为空。 Is this because the mock when() is not applying the second time?这是因为模拟 when() 没有第二次应用吗?
Apply your when() statement in your @Test directly on the PaymentsApi object.直接在 PaymentsApi 对象上应用 @Test 中的 when() 语句。
when(paymentsApi.getPayment("p1")).thenReturn(VALID_PAYMENT_RESPONSE);
You can't chain your method calls when using "when()".使用“when()”时不能链接方法调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.