我怎样才能模拟一个服务来抛出异常 returns 一个列表的方法?

how can I mock a service to throw an exception a method that returns a List?

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

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);
    }....

到目前为止工作得很好,服务实际用例的单元测试 return字符串列表工作正常。

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

如果我让 myService 调用 myRestClientService,其中 myRestClientService 抛出异常,我是否应该使用方法签名 "throws Exception"?

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

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

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

 will(throwException(myException));

可能没有必要模拟 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();
}