【发布时间】:2017-12-08 14:05:48
【问题描述】:
我想在我的整个应用程序上编写一个集成测试,并且只想模拟一个特定的方法: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?
}
}
【问题讨论】:
-
使用
MockRestServiceServer,见stackoverflow.com/questions/42409768/…和docs.spring.io/spring/docs/5.0.2.RELEASE/…
标签: java spring unit-testing junit spring-test