jeudi 4 juillet 2019

How to test a POSTing method by using an embedded Webserver in Springboot?

I am searching for a way to test a method, which sends a POST request to an external service. The application will NOT be itself a consumable webservice, that is why I didn't implement the shown class below as @RestController, @Controller, @Service, whatever types there may be.

But I don't know how to call the method postNumberPlate() to send a request to an embedded webserver (started in/by/at the unit test) to make some assertions on it. I want to avoid, to install an external webserver.

In other words: Can I start an embedded webserver inside a unit-test and 'tell' it to accept my POST request to inspect and assert the contents?

I already did:

  • a massive Webresearch (2-3 days?)
  • read Howto's
  • check the springboot docs
  • use an embedded Jetty Server (somehow blocking loop)
  • declare the Application as Webapplication and setting random port to jetty
  • experiment with Mockito, MockMVC
  • read "How to unittest a class using RestTemplate offline?" and compared it to my case, but found,
    • that it's very old (8y),
    • I don't know how to implement the parent interface, which is pretty huge
    • that the question and answers are too generic to deduce a solution for my case
    • it's not answering the embedded testing webserver problem I included.

The Class to be tested:

public class RestfulClient {

    private RestTemplate restTemplate = new RestTemplate();
    private HttpHeaders headers = new HttpHeaders();

    @Value("${kafkaeskadapter.uri}")
    private String destinationURL;

    public RestfulClient() {}

    public ResponseEntity<String> postNumberPlate(String key, CamImage camImage) {

        LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        map.add("numplate", camImage.getIdentifier());
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<LinkedMultiValueMap<String,
                Object>>(map, headers);

        ByteArrayResource resource = new ByteArrayResource(camImage.getData()) {
            /**
             * IMPORTANT!!! Otherwise I receive a BAD REQUEST
             * @return
             */
            @Override
            public String getFilename() {
                return camImage.getIdentifier() + ".png";
            }
        };
        map.add("image", resource);

        ResponseEntity<String> result = restTemplate.exchange(destinationURL, HttpMethod.POST,
                requestEntity, String.class);

        return result;
    }
}

I hope I could clarify my question a bit.

Aucun commentaire:

Enregistrer un commentaire