我在测试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块并引发异常?我将客户设置为空,但不起作用。
感谢您的帮助。
答案 0 :(得分:1)
您需要模拟该DAO调用并从那里抛出异常。
您将对@ Mock,@ InjectMock和@Mockito框架here有更多了解。
Mockito.when(getDataDao().update(any()))
.thenThrow(Exception.class);
答案 1 :(得分:0)
您可以使用 mockito 框架来实现。如果您是该框架的绝对入门者,那么我建议您参考以下教程。 Mockito - Exception Handling