相关疑难解决方法(0)

使用MockRestServiceServer模拟REST调用

我正在尝试编写一个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.

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

java rest junit spring

9
推荐指数
1
解决办法
2万
查看次数

标签 统计

java ×1

junit ×1

rest ×1

spring ×1