【问题标题】:How to mock http header in MockRestServiceServer?如何在 MockRestServiceServer 中模拟 http 标头?
【发布时间】:2018-05-22 19:56:21
【问题描述】:

我正在使用MockRestServiceServer 模拟外部 Web 服务 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));
    }

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

        以下代码对我有用:

        HttpHeaders mockResponseHeaders = new HttpHeaders();
        mockResponseHeaders.set("Authorization", mockAuthToken);
        
        mockServer
                .expect(once(), requestTo(testhUrl))
                .andExpect(method(HttpMethod.POST))
                .andRespond(withSuccess().headers(mockResponseHeaders));
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-05-03
          • 2019-12-11
          • 1970-01-01
          • 2020-05-15
          • 2016-10-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多