Java 模拟restTemplate getForObject

Java 模拟restTemplate getForObject,java,spring,junit,mockito,resttemplate,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/eng

我要求休息服务:

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

}

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

我将采用spring的方式,使用
MockRestServiceServer
模拟与spring
RestTemplate
的交互

确保您的服务不会通过自己创建RestTemplate来获取RestTemplate—它应该被注入

API文档包含一个使用示例

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


尝试模拟接口
RestOperations
,而不是类
RestTemplate
。另外,您确定模板正确地注入到PriceService中吗?另外,尝试使用
eq(…)
any()
和verify上的参数。另外,您可以发布PriceService的代码吗?我想您应该调用
priceServiceMock
而不是
runtimeService