Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
503 views
in Technique[技术] by (71.8m points)

java - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...