2015-10-20 181 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