gpt4 book ai didi

java - Mockito.when 在测试方法体内不起作用

转载 作者:行者123 更新时间:2023-12-01 16:17:52 29 4
gpt4 key购买 nike

我正在尝试测试我制作的发票类。到目前为止有效,但我在 falsePayCallKeepsPaidAtFalse 方法内部遇到问题。 Mockito.when方法对实际返回值没有任何影响。到目前为止,Mockitor.when 只在 setUp() 方法内部工作。

到目前为止我已经尝试过:从 setUp() 方法中删除 Mockitor.when 并在每个测试方法中调用它。在 setUp() 方法中将返回值设置为 false (这会产生影响)。检查问题是否出在实际的 Invoice 类中,事实并非如此。

public class InvoiceTest {
@Mock
private OrderManager orderManager;
private InvoiceManager invoiceManager;

private Invoice invoice;
private ArrayList<Integer> orderIds;

@BeforeEach
public void setUp() {
orderManager = mock(OrderManager.class);
invoiceManager = mock(InvoiceManager.class);

orderIds = new ArrayList<>();
orderIds.add(2);
orderIds.add(5);
invoice = new Invoice(
null,
null,
null,
null,
"VAT",
16,
false,
2,
orderIds,
"test",
LocalDate.now()
);

HashMap<Integer, Order> returnOrders = new HashMap();
returnOrders.put(2, mock(Order.class));
returnOrders.put(5, mock(Order.class));

when(orderManager.fetchNOrders(orderIds)).thenReturn(returnOrders);
when(invoiceManager.setInvoicePaid(invoice, orderIds)).thenReturn(true);

invoice.pay(invoiceManager, orderManager);
}
/**
* Pay.
*/
@Test
public void payCallsSetInvoicePaid() {
verify(invoiceManager, times(1)).setInvoicePaid(invoice, invoice.getOrders());
}

@Test
public void correctPayCallSetsPaidToTrue() {
invoiceManager.setInvoicePaid(invoice, orderIds);
assertThat(invoice.isPaid()).isTrue();
}

@Test
public void falsePayCallKeepsPaidAtFalse() {
when(invoiceManager.setInvoicePaid(invoice, orderIds)).thenReturn(false);

invoiceManager.setInvoicePaid(invoice, orderIds);
assertThat(invoice.isPaid()).isFalse();
}
@Test
public void payAsksForOrderFetch() {
verify(orderManager, times(1)).fetchNOrders(orderIds);
}
}

最佳答案

我发现了错误。我在 falsePayCallKeepsPaidAtFalse() 中调用了错误的方法。正确的是:invoice.pay(invoiceManger, orderManager);

关于java - Mockito.when 在测试方法体内不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62359171/

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