如何模拟RestTemplate的webservice响应?

mem*_*und 4 java junit spring unit-testing spring-test

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

我想从本地文件读取响应(以模拟和模仿外部服务器响应,因此它始终是相同的)。

我的本地文件应该只包含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?
   }
}
Run Code Online (Sandbox Code Playgroud)

mem*_*und 5

春天真是太棒了:

    @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));
    }
Run Code Online (Sandbox Code Playgroud)