Reputation: 86747
I'm using MockRestServiceServer
to mock an external webservice xml response.
That already works fine, but how can I also mock the http header inside the response, not only the response body?
@MockBean
private RestTemplate restTemplate;
private MockRestServiceServer mockServer;
@Before
public void createServer() throws Exception {
mockServer = MockRestServiceServer.createServer(restTemplate);
}
@Test
public void test() {
String xml = loadFromFile("productsResponse.xml");
mockServer.expect(MockRestRequestMatchers.anything()).andRespond(MockRestResponseCreators.withSuccess(xml, MediaType.APPLICATION_XML));
}
Upvotes: 7
Views: 8339
Reputation: 2015
The following codes work for me:
HttpHeaders mockResponseHeaders = new HttpHeaders();
mockResponseHeaders.set("Authorization", mockAuthToken);
mockServer
.expect(once(), requestTo(testhUrl))
.andExpect(method(HttpMethod.POST))
.andRespond(withSuccess().headers(mockResponseHeaders));
Upvotes: 0
Reputation: 545
@Gorazd's answer is correct. To add more flesh to it:
HttpHeaders headers = new HttpHeaders();
headers.setLocation(new URI(billingConfiguration.getBillingURL()+"/events/123"));
mockServer.expect(ExpectedCount.once(),
requestTo(new URI(billingConfiguration.getBillingURL())))
.andExpect(method(HttpMethod.POST))
.andRespond(withStatus(HttpStatus.OK)
.contentType(MediaType.APPLICATION_JSON).headers(headers));
Upvotes: 3
Reputation: 825
Just follow your withSuccess
method with headers
method.
mockServer
.expect(...)
.andRespond(withSuccess().headers(...));
Upvotes: 12