Java 我如何模拟一个服务来抛出一个异常,一个返回列表的方法?
我面临着这个小问题。我有这样的服务Java 我如何模拟一个服务来抛出一个异常,一个返回列表的方法?,java,unit-testing,junit,jmock,Java,Unit Testing,Junit,Jmock,我面临着这个小问题。我有这样的服务 public class Myservice { MyRestService myRestService; public List<String> getNames() throws RestClientException { return myRestService.getNames(); } .... 但我得到了一个错误,我不能从一个只返回列表的方法中抛出异常来解决这个问题?我怎样才能测试它 根据
public class Myservice {
MyRestService myRestService;
public List<String> getNames() throws RestClientException {
return myRestService.getNames();
}
....
但我得到了一个错误,我不能从一个只返回列表的方法中抛出异常来解决这个问题?我怎样才能测试它 根据文档,您应该使用
throweexception
而不是returnValue
。这意味着代码应该是
will(throwException(myException));
根据文档,您应该使用
throweexception
而不是returnValue
。这意味着代码应该是
will(throwException(myException));
可能没有必要模拟RestClientException。这条线可能会抛出一个非法的argumentException,然后停在那里。例如
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();
}
可能没有必要模拟RestClientException。这条线可能会抛出一个非法的argumentException,然后停在那里。例如
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();
}