gpt4 book ai didi

java - 为什么mockito认为我的服务被调用了两次?

转载 作者:行者123 更新时间:2023-12-01 19:27:50 25 4
gpt4 key购买 nike

我在使用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);
...
}

错误

Wanted 1 time: at com.squareup.square.SquareClient.getPaymentsApi(SquareClient.java:239) But was 2 times:

这看起来不错,但是当你看到这两个电话来自哪里时。 。 有人在服务

Payment payment = squareClient.getPaymentsApi().getPayment(paymentId).getPayment();

还有一个正在测试。为什么这个会在这里?

when(squareClient.getPaymentsApi().getPayment("p1")).thenReturn(VALID_PAYMENT_RESPONSE);

我的问题

  • 首先,应该只有 1 个调用。

  • 其次,当我检查两次 verify(squareClient, times(2)).getPayment("p1") 时,我得到一个空指针,因为getPaymentsApi() 现在为空。这是因为模拟when()没有第二次应用吗?

最佳答案

将@Test 中的when() 语句直接应用于PaymentsApi 对象。

when(paymentsApi.getPayment("p1")).thenReturn(VALID_PAYMENT_RESPONSE);

使用“when()”时无法链接方法调用。

关于java - 为什么mockito认为我的服务被调用了两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60934569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com