Search code examples
springmockmvcspring-test-mvc

spring mock mvc tests with api being invoked from external system


I have an api(API 1) which is being stubbed through MockMvc.When I post on this API through this mock object, a request goes out to external system which in turn invokes api (API 2) of my system. Since this API 2 is invoked through http channel (host:port) and the container is not running, this breaks. How do I handle this scenario since I would not prefer to change the way external system invokes my API. Hope I have clarified.


Solution

  • If you're using MockMvc, you cannot test calls over the network.

    So in that case, you would need to mock or stub the components that perform external network calls.

    On the other hand, if you are using Spring Boot... you can then have Spring Boot's testing support launch the embedded Servlet container for the test, and externals calls can connect to the running Servlet container over HTTP. For that however, you would typically use something like Spring Boot's TestRestTemplate or core Spring's WebTestClient (available since Spring Framework 5.0) instead of MockMvc.