2015-10-20 133 views
1

我的要求休息服務:嘲諷restTemplate getForObject

Price[] prices = restTemplate.getForObject("https://sbk02.test.sparebank1.no/sbk/rest/poc1/prices", Price[].class); 

我想嘲笑,但也有故作零個互動。我的測試代碼是:

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations={ "classpath:/spring/engine.xml", "classpath:/spring/beans.xml"}) 
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class, DirtiesMocksTestContextListener.class}) 
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) 
public class LabbOgLineProcessTest{ 
    @InjectMocks 
    private PriceService priceServiceMock; 
    @Mock 
    private RestTemplate template; 

    @Before 
    public void initMocks() throws Exception { 
     MockitoAnnotations.initMocks(this); 
    } 

    @Test 
    public void complete_AllTasks_success() throws Exception{ 
      when(template.getForObject(eq(PRICES_NAMESPACE), eq(Price[].class))).thenReturn(prices); 
      ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("process"); 
      verify(template, times(1)).getForObject(PRICES_NAMESPACE, Price[].class); 
    } 

} 
+0

嘗試嘲諷接口'RestOperations'代替類'RestTemplate'。另外,您確定模板正在PriceService中正確注入嗎?此外,請嘗試使用'eq(...)'或'any()'與verify中的參數。另外,你可以發佈PriceService的代碼嗎? – ESala

+0

我想你應該調用'priceServiceMock'而不是'runtimeService' – Ruben

回答

1

您的問題很可能是您的服務沒有使用模擬的RestTemplate,而是自行獲取實例。您可以發佈代碼進行澄清。

我會去春季的方式和使用MockRestServiceServer嘲笑彈簧RestTemplate互動。

確保您的服務不通過自己創建RestTemplate - 它應該被注入。

API文檔包含一個使用示例。

這樣你也可以測試你的JSON負載的反序列化。

http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/test/web/client/MockRestServiceServer.html