2017-03-29 34 views
1

我正面臨這個小問題。我有一個服務這樣我怎樣才能嘲笑一個服務拋出一個異常返回一個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); 
    }.... 

到目前爲止的工作這麼好,爲案件的單元測試的服務實際上 返回字符串作品列表精細。

但由於服務調用另一個基本上是可以拋出異常的休息客戶端,我想嘲笑這種情況。

如果我有我的服務調用myRestClientService其中myRestClientService拋出一個異常,應該我的方法簽名「拋出異常」?

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

但我得到一個錯誤,我不能從只返回List的方法拋出異常來解決這個問題嗎?我怎麼測試它?

回答

0

它可能沒有必要嘲笑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(); 
} 
相關問題