membersound
membersound

Reputation: 86747

How to mock http header in MockRestServiceServer?

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

Answers (3)

Vikki
Vikki

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

cs94njw
cs94njw

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

Gorazd Rebolj
Gorazd Rebolj

Reputation: 825

Just follow your withSuccess method with headers method.

mockServer
       .expect(...)
       .andRespond(withSuccess().headers(...));

Upvotes: 12

Related Questions