How do I test my service which is calling a 3 party rest endpoint?

Viewed 227

I'm trying to test my service which is sending a rest request to a 3rd party rest endpoint which is mocked during the integration testing (Assume that I know the required Request Body). The code provided is only a rough outline of what I'm trying to achieve. The rest endpoint itself may not be available at all times, which is why I want to mock it. Let's look at the pseudo-code:

First my test case:

public class FooExampleTest {

    private ExampleService exampleService;

    @BeforeEach
    void setup() {
        
        exampleService = new ExampleService();
        
    }

    @Test
    void example_TestCase() {

        SomeEntity entity = new SomeEntity();
        entity.setFoo("Foo!");
        // set more fields....
  
        // Calling the service containing the rest request to the 3rd party system
        exampleService.sendToClient(entity);

    }
}

The service containing the request to the 3rd party system is mocked

@Service
public class SomeServiceImpl {
  
    // some fields
    // ...
    @Autowired
    private RestTemplate restTemplate;


   // ......


    public void sendToClient(Entity entity){
        var uri = "http://localhost:8080/foo"
        var clientSystem = new ClientSystemRequest();
        clientSystem.setImportField(entity)
        log.info("Sending reqeust to client system");
        
        restTemplate.postForObject(uri, clientSystem, ClientSystemResponse.class);
    }

}

The 3rd party rest endpoint should be mocked during integration testing


@RestController
@Slf4j
/**
 * Mocks the 3rd party rest endpoint
 */
public class 3rdPartyClientsystemResourceTest {
    

    @PostMapping("/foo")
    public ResponseEntity<?> foo(@RequestBody @Valid ClientSystemRequest clientSystemRequest){
        log.info("Received, with data: {}", clientSystemRequest);
        
        // Do some sort of validation....

        return new ResponseEntity<>(HttpStatus.OK);
    }


}

1 Answers

Have you looked into using mocking frameworks such as Mockito for example? You could then simply mock the restTemplate and only test the logic of your service rather than it's communication with API.

If you want an integration test than you must make the real call to the API. Otherwise it isn't an integration test.

Related