我正在使用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));
}
答案 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));