Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking a REST call with MockRestServiceServer

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.

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

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

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

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

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

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.

Spring version 4.1.7.

Thanks in advance for any assistance.

like image 268
GarlicBread Avatar asked Jun 13 '16 04:06

GarlicBread


1 Answers

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.

like image 77
Rafal G. Avatar answered Sep 27 '22 22:09

Rafal G.