Mock REST call with MockRestServiceServer

I am trying to write a JUnit test case that tests a method in a helper class. The method calls an external application using REST, and I am trying to model this call in a JUnit test.

The helper method makes a REST call using the Spring RestTemplate.

In my test, I create a dummy REST server and a dummy REST template and instantiate them as follows:

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

Then I start the dummy server so that it returns the appropriate response when the helper method makes a 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 gets a null response from the REST call it makes, and the test fails.

URL REST, , : " http://: //? Queryparam1 = 1 & queryparam2 = 2 ".

URL- (" http://server: port/application/resource ") , "myURL" ( , ), .

, .

4.1.7.

.

+9
3

MockRestServiceServer, RestTemplate, . RestTemplate MockRestServiceServer.createServer - RestTemplate .

+10

, -, - . RestTemplate → . RestTemplate .

@Mock
RestTemplate restTemplateMock;

@InjectMocks
Service service;

,

public void filterData() {
   MyResponseModel response = restTemplate.getForObject(serviceURL, MyResponseModel.class);
   // further processing with response
}

, filterData, restTemplate,

mockResponseModel = createMockResponse();
Mockito.when(restTemplateMock.getForObject(serviceURL, MyResponseModel.class)).thenReturn(mockResponseModel);

service.filterData();
//Other assert/verify,... go here
+4

You can create a new instance of RestTemplate, however you must pass it to your createServer method as follows:

private RestTemplate restTemplate = new RestTemplate();
@BeforeEach
public void setUp() {
MockitoAnnotations.initMocks(this);
mockServer = MockRestServiceServer.createServer(restTemplate);
client.setRestTemplate(restTemplate);
}
0
source

All Articles