测试使用 Spring 服务的方法。

huangapple go评论63阅读模式
英文:

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&#39;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

huangapple
  • 本文由 发表于 2020年8月27日 04:48:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/63605514.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定