测试使用Spring服务的方法

问题描述

我在测试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块并引发异常?我将客户设置为空,但不起作用。

感谢您的帮助。

解决方法

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

您将对@ Mock,@ InjectMock和@Mockito框架here有更多了解。

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

您可以使用 mockito 框架来实现。如果您是该框架的绝对入门者,那么我建议您参考以下教程。 Mockito - Exception Handling

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...