Java – simulate rest calls using mockrestserviceserver

I am trying to write a JUnit test case to test the methods in the auxiliary class This method uses rest to call external applications, which I tried to simulate in JUnit testing

Auxiliary methods use spring's resttemplate for rest calls

In my test, I created a simulated rest server and simulated rest templates and instantiated them as:

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

Then I seed the mock server so that when the helper method makes a rest call, it should return an appropriate response:

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

When I run my test, the helper method receives an empty response from its rest call and the test fails

The rest URL generated by the helper has query parameters as follows:“ http://server:port/application/resource?queryparam1=value1&queryparam2=value2 ”.

I've tried to convert URLs with and without query parameters(“ http://server:port/application/resource ”)Put it in the "myurl" variable (to elicit a match so that it returns a response), but you can't let the impersonation server return anything

I've tried searching for examples of this code, but I haven't found anything that looks like my scene

Spring version 4.1 seven

Thank you for your help

Solution

When creating an instance of mockrestserviceserver, you should use the existing resttemplate instance that your production code is using Therefore, try to inject resttemplate into the test and call mockrestserviceserver Use it when creating the server – do not create a new resttemplate in the test

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>