2017-04-05 154 views
1

我有一個restTemplate的服務方法。作爲單元測試的一部分,我試圖嘲笑它,但一些失敗。RestTemplate的單元測試模擬

服務方法:

@Autowired 
private RestTemplate getRestTemplate; 

return getRestTemplate.getForObject(restDiagnosisGetUrl, SfdcCustomerResponseType.class); 

測試方法:

private CaresToSfdcResponseConverter caresToSfdcResponseConverter; 

    @Before 
    public void setUp() throws Exception { 
     caresToSfdcResponseConverter = new CaresToSfdcResponseConverter(); 

    } 
    @Test 
    public void testConvert(){ 
    RestTemplate mock = Mockito.mock(RestTemplate.class); 
     Mockito.when(mock.getForObject(Matchers.anyString(), Matchers.eq(SfdcCustomerResponseType.class))).thenReturn(sfdcCustomerResponseType); 
} 
sfdcRequest = caresToSfdcResponseConverter.convert(responseForSfdcAndHybris); 

這是給NullPointerException異常。看起來它是無法模擬休息模板,它正在休息模板爲空。任何幫助將不勝感激。謝謝

回答

1

這不是無法嘲笑其餘模板,但它不會將嘲笑休息模板注入您的生產類。至少有兩種方法可以解決這個問題。

您可以更改您的生產代碼和use constructor injection。移動RestTemplate給構造函數作爲參數,那麼你可以通過模擬測試:

@Service 
public class MyService { 
    @Autowired 
    public MyService(RestTemplate restTemplate) { 
     this.restTemplate = restTemplate; 
    } 
} 

在您的測試,你會簡單地創建服務爲任何其他對象,並通過它你嘲笑休息模板。

或者你可以改變你的測試使用下面的註釋注入您的服務:

@RunWith(MockitoJUnitRunner.class) 
public class MyServiceTest { 
    @InjectMocks 
    private MyService myService; 

    @Mock 
    private RestTemplate restTemplate; 

    @Test 
    public void testConvert(){ 
     Mockito.when(mock.getForObject(Matchers.anyString(), Matchers.eq(SfdcCustomerResponseType.class))).thenReturn(sfdcCustomerResponseType); 
    } 
} 

你可以看到在另一個SO問題的例子:Using @Mock and @InjectMocks

我一般喜歡構造函數注入。

+0

謝謝@ sm4。這完美的工作。我已經嘗試過這種注入模擬的方式,但不知何故,它不工作。所以通過在谷歌中進行一些搜索來改變其他。再次感謝。 – arjun