如何模拟 RestTemplate 的 webservice 响应?

How to mock the webservice response of RestTemplate?

我想对我的整个应用程序编写一个集成测试,并且只想模拟一个特定的方法:RestTemplate 我用来将一些数据发送到外部网络服务并接收响应的方法。

我想从本地文件读取响应(模拟和模拟外部服务器响应,所以它总是一样的)。

我的本地文件应该只包含在生产环境中外部网络服务器会响应的json/xml响应。

问题:如何模拟外部 xml 响应?

@Service
public class MyBusinessClient {
      @Autowired
      private RestTemplate template;

      public ResponseEntity<ProductsResponse> send(Req req) {
               //sends request to external webservice api
               return template.postForEntity(host, req, ProductsResponse.class);
      }
}

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class Test {

   @Test
   public void test() {
        String xml = loadFromFile("productsResponse.xml");
        //TODO how can I tell RestTemplate to assume that the external webserver responded with the value in xml variable?
   }
}

您可以为此实现像 Mockito 这样的模拟框架:

因此,在您的 resttemplate mock 中,您将拥有:

when(restTemplate.postForEntity(...))
    .thenAnswer(answer(401));

并回答实现,例如:

private Answer answer(int httpStatus) {
    return (invocation) -> {
        if (httpStatus >= 400) {
            throw new RestClientException(...);
        }
        return <whatever>;
    };
}

如需进一步阅读,请关注 Mockito

Spring太棒了:

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