如何在MockRestServiceServer中模拟http标头?

时间:2017-12-08 14:42:09

标签: java spring spring-boot junit spring-test

我正在使用MockRestServiceServer来模拟外部webservice xml响应。 这已经很好了,但我怎么能在响应中模拟 http标题,而不仅仅是响应体?

    @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));
    }

3 个答案:

答案 0 :(得分:4)

只需使用withSuccess方法关注headers方法。

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

答案 1 :(得分:1)

@Gorazd的回答是正确的。要添加更多的肉,

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));

答案 2 :(得分:0)

以下代码对我有用:

HttpHeaders mockResponseHeaders = new HttpHeaders();
mockResponseHeaders.set("Authorization", mockAuthToken);

mockServer
        .expect(once(), requestTo(testhUrl))
        .andExpect(method(HttpMethod.POST))
        .andRespond(withSuccess().headers(mockResponseHeaders));