使用MockRestServiceServer模拟REST调用

Gar*_*ead 9 java rest junit spring

我正在尝试编写一个JUnit测试用例,用于测试辅助类中的方法.该方法使用REST调用外部应用程序,这是我试图在JUnit测试中模拟的调用.

辅助方法使用Spring的RestTemplate进行REST调用.

在我的测试中,我创建了一个模拟REST服务器并模拟REST模板并将它们实例化为:

@Before
public void setUp() throws Exception {
    mockServer = MockRestServiceServer.createServer(helperClass.getRestTemplate());
}
Run Code Online (Sandbox Code Playgroud)

然后我为mock服务器播种,以便在helper方法进行REST调用时它应该返回一个适当的响应:

// response is some XML in a String
mockServer
    .expect(MockRestRequestMatchers.requestTo(new URI(myURL)))
    .andExpect(MockRestRequestMatchers.method(HttpMethod.GET))
    .andRespond(MockRestResponseCreators.withStatus(HttpStatus.OK)
        .contentType(MediaType.APPLICATION_XML)
        .body(response));
Run Code Online (Sandbox Code Playgroud)

当我运行我的测试时,helper方法从它所做的REST调用中接收一个空响应,并且测试失败.

帮助程序生成的REST URL具有查询参数,如下所示:" http:// server:port/application/resource?queryparam1 = value1&queryparam2 = value2 ".

我已经尝试将带有不带有查询参数的URL(" http:// server:port/application/resource ")放在"myURL"变量中(以引出匹配以便它返回响应),但是可以不让模拟服务器返回任何东西.

我试过搜索这种代码的例子,但还没有找到任何看起来像我的场景的东西.

Spring版本4.1.7.

在此先感谢您的任何帮助.

Raf*_* G. 11

创建实例时,MockRestServiceServer应使用RestTemplate生产代码正在使用的现有实例.因此,尝试注入RestTemplate您的测试并在调用时使用它MockRestServiceServer.createServer- 不要RestTemplate在测试中创建新的.

  • 我也面临着测试 RestTemplate 的问题。但是,就我而言,我无权访问 RestTemplate 实例。我的助手类中的代码类似于`new RestTemplate().exchange(uri,HttpMethod.GET,...)`。我怎样才能测试这个。 (2认同)