【问题标题】:Mocking restTemplate getForObject模拟restTemplate getForObject
【发布时间】:2015-10-20 16:46:08
【问题描述】:

我的休息服务请求:

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

}

【问题讨论】:

  • 尝试模拟接口RestOperations 而不是类RestTemplate。另外,您确定在 PriceService 中正确注入了模板吗?此外,尝试使用 eq(...) 或 any() 与验证的参数。另外,能把PriceService的代码贴出来吗?
  • 我猜你应该打电话给priceServiceMock而不是runtimeService

标签: java spring junit mockito resttemplate


【解决方案1】:

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

我会采用 spring 方式并使用 MockRestServiceServer 模拟与 spring RestTemplate 的交互。

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-21
    • 1970-01-01
    • 2022-01-18
    • 2018-01-16
    • 1970-01-01
    • 2014-08-04
    • 2020-07-23
    • 2022-01-22
    相关资源
    最近更新 更多