7

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));
    }
membersound
  • 81,582
  • 193
  • 585
  • 1,120

3 Answers3

11

Just follow your withSuccess method with headers method.

mockServer
       .expect(...)
       .andRespond(withSuccess().headers(...));
Gorazd Rebolj
  • 803
  • 6
  • 10
2

@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));
cs94njw
  • 535
  • 5
  • 12
0

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));
Vikki
  • 1,897
  • 1
  • 17
  • 24