简体   繁体   中英

How to mock response of Rest call in spring when you can't controll when the RestTemplate is constructed

I want to write an integration level test for a rest method using MockRestServiceServer. My rest method is a proxy, it ends up creating a restTemplate via a static helper method and proxys the request to a third party. I want to mock out that third party. Actually two different rest calls are made to different parties with different configurations to service the request.

I want to use MockRestServiceServer, but it expects me to pass in the restTemplate, which is constructed within my integration test. I can try to use mocks to ensure that my own restTemplate is used, but now I have to pull in 4 new maven packages and write a bit of code to do the inject safely, and make sure that a different restTemplate is used for the two different external service calls my proxy does. It also requires me to know a little bit about my code and thus makes my integration test less of a black box then I would prefer.

Is there a cleaner way to mock the services? I know my approach could work, but it's just feeling overly cumbersome. Is there a way to mock this without having to inject the RestTemplate ahead of time?

If you don't want to redesign the part where you create instances of RestTemplate then you can parametrize out address of the external service and mock the entire external service using tools like Wiremock.

Using Wiremock, you actually run an embedded HTTP Server on a specific port. You can also tell Wiremock to return specified response when predefined request is made. It basically is just a mock, but over HTTP.

This way you would get a good integration test that would not only test your typical Java code but also entire communication (like JSON (de)serialization). I use Wiremock (and related) extensively at work and they do work like a charm.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM