Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock the webservice response of RestTemplate? [duplicate]

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?
   }
}
like image 870
membersound Avatar asked Sep 06 '25 03:09

membersound


1 Answers

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));
    }
like image 146
membersound Avatar answered Sep 07 '25 20:09

membersound