We are using RestTemplate to consume external rest services. There lot of different kinds of services in our project and all of them are tested using different strategies like mocking rest template and mocking our communication object.
We have used below code in our test case to test one service using MockRestServiceServer :
RestTemplate restTemplate = new RestTemplate();
mockServer = MockRestServiceServer.createServer(restTemplate);
So our question is : Is there a way to destroy this server as soon as this test case completes so this doesn't affect other test cases?
First and foremost, the MockRestServiceServer is not a real server -- for example, it is not listening on a TCP port. The only thing the MockRestServiceServer does is modify your RestTemplate (see details below).
So to answer your question: there is no server to destroy.
However... if your RestTemplate is created in your ApplicationContext and injected into multiple components (e.g., in your service layer), you may want to reset the initial state of the RestTemplate. If that's the case, read on...
There is currently no "official" way to reset the RestTemplate passed to MockRestServiceServer.createServer(), but that doesn't mean you can't implement such a feature on your own.
The key to understanding this is knowing that the MockRestServiceServer.createServer() method replaces the ClientHttpRequestFactory in the provided RestTemplate with a mocked version (i.e., the private, internal MockRestServiceServer.RequestMatcherClientHttpRequestFactory).
So you should be able to reset the original state of the RestTemplate by tracking the original request factory and setting it in the template after your test. Something like the following should work:
RestTemplate restTemplate = // likely injected into the test
ClientHttpRequestFactory originalRequestFactory = restTemplate.getRequestFactory();
MockRestServiceServer mockServer = MockRestServiceServer.createServer(restTemplate);
try {
// use mockServer as usual...
mockServer.verify();
} finally {
restTemplate.setRequestFactory(originalRequestFactory);
}
Let me know if that solves your problem!
Cheers,
Sam (author of the Spring TestContext Framework)
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