Java 如何模拟RestTemplate的webservice响应?
我想对我的整个应用程序编写一个集成测试,并且只想模拟一个特定的方法:我用来向外部Web服务发送一些数据并接收响应的Java 如何模拟RestTemplate的webservice响应?,java,spring,unit-testing,junit,spring-test,Java,Spring,Unit Testing,Junit,Spring Test,我想对我的整个应用程序编写一个集成测试,并且只想模拟一个特定的方法:我用来向外部Web服务发送一些数据并接收响应的restemplate 我希望从本地文件中读取响应(模拟和模拟外部服务器响应,因此总是相同的) 我的本地文件应该只包含外部Web服务器在生产中响应的json/xml响应 问题:如何模拟外部xml响应 @Service public class MyBusinessClient { @Autowired private RestTemplate template
restemplate
我希望从本地文件中读取响应(模拟和模拟外部服务器响应,因此总是相同的)
我的本地文件应该只包含外部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?
}
}
@服务
公共类MyBusinessClient{
@自动连线
私有rest模板;
公共响应发送(Req Req){
//将请求发送到外部webservice api
返回模板.postForEntity(主机、请求、产品响应.class);
}
}
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=SpringBootTest.webEnvironment.RANDOM\u端口)
公开课考试{
@试验
公开无效测试(){
字符串xml=loadFromFile(“productsResponse.xml”);
//TODO如何让RestTemplate假定外部Web服务器使用xml变量中的值进行响应?
}
}
您可以实现类似Mockito的模拟框架,用于:
因此,在resttemplate模拟中,您将有:
when(restTemplate.postForEntity(...))
.thenAnswer(answer(401));
然后回答如下问题:
private Answer answer(int httpStatus) {
return (invocation) -> {
if (httpStatus >= 400) {
throw new RestClientException(...);
}
return <whatever>;
};
}
私人应答(int-httpStatus){
返回(调用)->{
如果(httpStatus>=400){
抛出新的RestClientException(…);
}
返回;
};
}
如需进一步阅读,请参见《春天如此美妙》:
@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));
}
使用
MockRestServiceServer
,请参阅:OP希望模拟原始web服务XML响应,而不是RestTemplate
返回的经过解析和实例化的对象。