英文:
Test a method that use a spring service
问题
我在Java中有一个问题,测试一个方法(我使用jUnit 4),这个方法在测试时会调用一个存储库,如果出现问题应该抛出异常,这个方法看起来像是这样的:
```java
// 该方法位于Spring服务中,使用存储库进行查询
public void updateCustomer(CustomerEntity customer) throws CustomException {
try {
getDataDao().update(customer);
} catch (Exception e) {
throw new CustomException(e.getMessage());
}
}
问题是,我如何让测试用例进入catch块并抛出异常?我将customer设置为null,但不起作用。
谢谢您的帮助。
<details>
<summary>英文:</summary>
I have a problem testing a method in Java (I use jUnit 4) and this method to test make a call to a repository and should throw an exception if something is wrong, the method looks like:
//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());
}
}
The question is, How can I make for the test case enter the catch block and throw the exception? I am setting the customer to null but don't work.
Thanks for your help.
</details>
# 答案1
**得分**: 1
你需要对那个DAO调用进行模拟,并从那里抛出一个异常。
你可以在这里更多地了解关于@Mock、@InjectMock和[Mockito][1]框架的内容。
```java
Mockito.when(getDataDao().update(any()))
.thenThrow(Exception.class);
英文:
You need to mock that DAO call and throw and exception from there.
You will get more idea about @Mock, @InjectMock and @Mockito framework here.
Mockito.when(getDataDao().update(any()))
.thenThrow(Exception.class);
答案2
得分: 0
你可以使用 mockito 框架来实现这一点。如果你是这个框架的绝对初学者,我建议你参考下面的教程。
Mockito - 异常处理
英文:
You can achieve this using the mockito framework.If you are an absolute beginner for this framework ,then I recommend you to refer the following tutorials.
Mockito - Exception Handling
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论