【问题标题】:how can I mock a service to throw an exception a method that returns a List?如何模拟服务以抛出异常返回列表的方法?
【发布时间】:2017-04-04 18:31:34
【问题描述】:

我正面临这个小问题。我有这样的服务

public class Myservice {

   MyRestService myRestService; 

    public List<String> getNames() throws RestClientException {
        return myRestService.getNames();
    }

....

还有一个这样的控制器:

@RequestMapping(value = URL, method = GET)
    public ModelAndView display(final ModelMap model) {
        ....
        try{
            List<String> listOfNames = myService.getNames();
        }catch(RestClientException e){
            LOG.error("Error when invoking Names service", e);
        }
        model.addAttribute("names", listOfNames);
        return new ModelAndView(VIEW, model);
    }....

到目前为止效果很好,服务案例的单元测试实际上 返回一个字符串列表工作正常。

但由于该服务调用另一个基本上是可能引发异常的休息客户端的服务,我想模拟这种情况。

如果我有 myService 调用 myRestClientServicemyRestClientService 抛出异常,我应该对方法签名“抛出异常”吗?

 final RestClientException myException =  mockery.mock(RestClientException.class);
        mockery.checking(new Expectations() {
            {
                oneOf(myService).getNames();
                will(returnValue(myException));
...

但是我得到一个错误,我不能从一个只返回 List 的方法中抛出异常,无论如何要解决这个问题吗?我怎么能测试它?

【问题讨论】:

    标签: java unit-testing junit jmock


    【解决方案1】:

    根据文档Throwing Exceptions from Mocked Methods,您应该使用throwException 而不是returnValue。这意味着代码应该类似于

     will(throwException(myException));
    

    【讨论】:

      【解决方案2】:

      可能没有必要模拟 RestClientException。该行可能会抛出 IllegalArgumentException 并停在那里。例如

      java.lang.IllegalArgumentException: org.springframework.web.client.RestClientException is not an interface
      

      一个有效的示例可能如下所示:

      @Test(expected = RestClientException.class)
      public void testDisplayThrowException() throws Exception {
          MyService myService = mockery.mock(MyService.class);
      
          mockery.checking(new Expectations() {
              {
                  allowing(myService).getNames();
                  will(throwException(new RestClientException("Rest client is not working")));
              }
          });
      
          myService.getNames();
      }
      

      【讨论】:

        猜你喜欢
        • 2018-01-13
        • 1970-01-01
        • 2017-02-12
        • 1970-01-01
        • 1970-01-01
        • 2023-03-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多