Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在MockRestServiceServer中模拟http头?_Java_Spring_Spring Boot_Junit_Spring Test - Fatal编程技术网

Java 如何在MockRestServiceServer中模拟http头?

Java 如何在MockRestServiceServer中模拟http头?,java,spring,spring-boot,junit,spring-test,Java,Spring,Spring Boot,Junit,Spring Test,我正在使用MockRestServiceServer模拟外部webservice xml响应。 这已经很好了,但是我如何在响应内部模拟http头,而不仅仅是响应体 @MockBean private RestTemplate restTemplate; private MockRestServiceServer mockServer; @Before public void createServer() throws Exception {

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

只需按照您的
withSuccess
方法和
headers
方法即可

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

@戈拉日德的回答是正确的。要添加更多内容:

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

以下代码适用于我:

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

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