测试使用 spring 服务的方法

Test a method that use a spring service

我在 Java 中测试方法时遇到问题(我使用 jUnit 4),此方法用于测试对存储库的调用,如果有问题应该抛出异常,该方法如下所示:

//Method located in a Spring service and use a repository to make the query
public void updateCustomer(CustomerEntity customer) throws CustomException {
        try {
            getDataDao().update(customer);
        } catch (Exception e) {
            throw new CustomException(e.getMessage());
        }
    }

问题是,如何让测试用例进入catch块并抛出异常?我正在将客户设置为 null 但不起作用。

感谢您的帮助。

您需要模拟该 DAO 调用并从那里抛出异常。

您将对@Mock、@InjectMock 和@Mockito framework here有更多了解。

  Mockito.when(getDataDao().update(any()))
      .thenThrow(Exception.class);

您可以使用 mockito framework.If 您是这个框架的绝对初学者,那么我建议您参考以下教程。 Mockito - Exception Handling