模拟restTemplate getForObject

时间:2015-10-20 16:46:08

标签: java spring junit mockito resttemplate

我要求休息服务:

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

我试图模仿它,但与mock没有任何交互。我的测试代码是:

@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);
    }

}

1 个答案:

答案 0 :(得分:1)

您的问题很可能是您的服务没有使用模拟的RestTemplate,而是自己获取实例。您可以发布代码以便澄清。

我会采用春天方式并使用MockRestServiceServer模拟与春天RestTemplate的互动。

确保您的服务没有通过自己创建RestTemplate获得 - 它应该被注入。

API文档包含一个用法示例。

这样您还可以测试JSON有效负载的反序列化。

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