使用MockRestServiceServer模拟REST调用 [英] Mocking a REST call with MockRestServiceServer

查看:456
本文介绍了使用MockRestServiceServer模拟REST调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to write a JUnit test case which tests a method in a helper class. The method calls an external application using REST and it's this call that I am trying to mock in the JUnit test.

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

The helper method makes the REST call using Spring's RestTemplate.

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

In my test, I create a mock REST server and mock REST template and instanitiate them like this:

@Before
public void setUp() throws Exception {
    mockServer = MockRestServiceServer.createServer(helperClass.getRestTemplate());
}

然后我给模拟服务器添加种子,以便当助手方法进行REST调用时它应返回适当的响应:

I then seed the mock server so that it should return an appropriate response when the helper method makes the REST call:

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

运行测试时,helper方法从其进行的REST调用接收到空响应,并且测试失败.

When I run my test, the helper method receives a null response from the REST call it makes and the test fails.

助手创建的REST URL具有查询参数,如下所示:" http://server:port/application/resource?queryparam1 = value1& queryparam2 = value2 ".

The REST URL that the helper makes has query params and looks like this: "http://server:port/application/resource?queryparam1=value1&queryparam2=value2".

我尝试将URL(" http://server:port/application/resource "),同时在和中都没有在"myURL"变量中使用查询参数(引发匹配以使其返回响应),但是无法使模拟服务器返回任何内容.

I've tried putting the URL ("http://server:port/application/resource") both with and without the query parameters in the "myURL" variable (to elicit a match so that it returns a response), but can not get the mock server to return anything.

我曾尝试搜索此类代码的示例,但尚未找到任何看起来与我的情况相似的东西.

I've tried searching for examples of this kind of code but have yet to find anything which seems to resemble my scenario.

春季版本4.1.7.

在此先感谢您的帮助.

推荐答案

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

When you create an instance of MockRestServiceServer you should use existing instance of RestTemplate that is being used by your production code. So try to inject RestTemplate into your test and use it when invoking MockRestServiceServer.createServer - don't create new RestTemplate in your tests.

这篇关于使用MockRestServiceServer模拟REST调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆