Home > database >  Test of endpoint that sends a request to external api
Test of endpoint that sends a request to external api

Time:02-05

There is a small method mymethod that gets the response from the external api data in json format, which will be Dto and then there is a getEnums method that selects which data to leave and returns a list of strings and as a result mymethod itself returns a list of strings. I tried to write a test, but I get :

Expected :200

Actual :302

As I understand the problem is in the redirection, but how to solve it I do not understand, maybe you have an answer?

controller

@GetMapping(value = "api/mymethod", produces = "application/json")
    public ResponseEntity<List<String>> mymethod(@RequestHeader(value = "Enum") String Enum,
                                                @RequestParam(value = "Type") String Type) {

        URI uri = UriComponentsBuilder.fromUriString("...url...").build().toUri();

        HttpHeaders headers = new HttpHeaders();

        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<String> entity = new HttpEntity<>(null, headers);

        ResponseEntity<myDto> response =
                restTemplate.exchange(uri, HttpMethod.GET, entity, myDto.class);

        List<String> currencies = 
                getEnums(response, Type); // <- custom method
        return new ResponseEntity<>(currencies, HttpStatus.OK);
}

// (The test is not written in full, left exactly the problem area)

test

  @Test
    public void mytest() throws Exception{

        ResultActions getResult = mockMvc.perform(get("/api/mymethod")
                        .header("Enum", "OOL")
                        .param("Type", "Counter"))
                .andExpect(status().isOk());

    }

CodePudding user response:

The problem with testing against an external service is that you do not manage it's state. Therefore your test cases may show varying results even if you did not change anything.

Usually you'd create a mock of the REST api your test object would access. Then you can send requests to your test object and check in the mocked api whether the expected requests did come in. You can also fake success or error responses and check how your test object reacts.

To finally answer your question: How do you want your client to treat a redirection? Should it follow or error out? Looking at the meaning of status 302 it means the resource has moved temporarily or at least was found at a new location. This might mean a valid redirect if the server is trying to loadbalance or tries to point out a url that is closer to you network-wise. Therefore I believe the client should follow a 302.

  •  Tags:  
  • Related