I am facing this little issue. I have a service this way
public class Myservice {
MyRestService myRestService;
public List<String> getNames() throws RestClientException {
return myRestService.getNames();
}
....
and a controller that is like this:
@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);
}....
So far works so good, the unit testing for the case the service actually returns a list of Strings works fine.
But since the service calls another one that is basically a rest client that could throw an exception, I want to mock that case.
If I have myService calling myRestClientService
where myRestClientService
throws an exception should I hadd to the method signature "throws Exception" ?
final RestClientException myException = mockery.mock(RestClientException.class);
mockery.checking(new Expectations() {
{
oneOf(myService).getNames();
will(returnValue(myException));
...
But I get an error that I cannot throw an exception from a method that only return List is there anyway to fix this? How could I test it?
According to the documentation Throwing Exceptions from Mocked Methods you should use throwException
rather than returnValue
. It means code should be something like
will(throwException(myException));