【问题标题】:How to throw an exception based on some condition in Junit 5?如何根据 Junit 5 中的某些条件抛出异常?
【发布时间】:2022-10-13 21:06:33
【问题描述】:

我有一个带有 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 或任何其他方式中使用?

请建议。

【问题讨论】:

  • 模拟 CustomerRepo。我建议 Mockito。

标签: java spring-boot unit-testing junit mockito


【解决方案1】:

Mockito 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));
}

【讨论】:

    猜你喜欢
    • 2017-03-09
    • 2022-06-29
    • 2016-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    • 2016-05-06
    相关资源
    最近更新 更多