Below is an example:
RestTemplate restTemplate = new RestTemplate() MockRestServiceServer mockServer = MockRestServiceServer.createServer(restTemplate); mockServer.expect(requestTo("/hotels/42")).andExpect(method(HttpMethod.GET)) .andRespond(withSuccess("{ \"id\" : \"42\", \"name\" : \"Holiday Inn\"}", MediaType.APPLICATION_JSON)); Hotel hotel = restTemplate.getForObject("/hotels/{id}", Hotel.class, 42); // Use the hotel instance... mockServer.verify();To create an instance of this class, use {@link #createServer(RestTemplate)}and provide the {@code RestTemplate} to set up for the mock testing.
After that use {@link #expect(RequestMatcher)} and fluent API methods{@link ResponseActions#andExpect(RequestMatcher) andExpect(RequestMatcher)} and{@link ResponseActions#andRespond(ResponseCreator) andRespond(ResponseCreator)}to set up request expectations and responses, most likely relying on the default {@code RequestMatcher} implementations provided in {@link RequestMatchers}and the {@code ResponseCreator} implementations provided in{@link ResponseCreators} both of which can be statically imported.
At the end of the test use {@link #verify()} to ensure all expectedrequests were actually performed.
Note that because of the fluent API offered by this class (and related classes), you can typically use the Code Completion features (i.e. ctrl-space) in your IDE to set up the mocks.
Credits: The client-side REST testing support was inspired by and initially based on similar code in the Spring WS project for client-side tests involving the {@code WebServiceTemplate}. @author Craig Walls @author Rossen Stoyanchev
|
|
|
|