I'd like to write an integration test on my whole application, and want to mock only one specific method: the RestTemplate
that I use to send some data to an external webservice and receive the response.
I want to read the response instead from a local file (to mock and mimic the external server response, so it is always the same).
My local file should just contain thejson/xml
response that in production the external webserver would respond with.
Question: how can I mock an external xml response?
@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?
}
}
Spring is so great:
@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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With