我有一個帶有 Junit 5 和 Mockito 的 Spring Boot 應用程式。
我有下面的代碼。
@Autowired
CustomerRepo customerRepo;
public UpdatedCustomer updateCustomer(Customer customer) {
UpdatedCustomer updCustomer = new UpdatedCustomer();
updCustomer.setId(customer.getId());
//some more setters
//Here I need to throw exceptions for the customer whose id is 5 only. Can I do this in mockito or any other framework?
customerRepo.save(updCustomer);
return updCustomer;
}
我需要為上面代碼中 ID 為 5 的客戶拋出例外,而其他客戶則應呼叫 save 的實際實作。在 SpyBean 或任何其他方式中是否有可能?
請建議。
uj5u.com熱心網友回復:
InMockito ArgumentMatcher是一個功能介面,您可以使用argThat匹配器。
@Mock
private CustomerRepo customerRepo;
@Test
void updateCustomerThrowsException() {
doThrow(RuntimeException.class)
.when(customerRepo).save(argThat(customer -> customer.getId() == 5));
var customer = new Customer();
customer.setId(5);
assertThrows(RuntimeException.class, () -> updateCustomer(customer));
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/464437.html
