简体   繁体   中英

is there a way to test all 5XX or 4XX codes with Mockito?

Hi everyone I'm working in a microservice which has dependency in another ones. I'm handling the rest consumption with Restemplate and everything its okay with that but I also need get a 100% on sonar test coverage.

On test stuff I'd like to cover any possibility of 4XX or 5XX code to be sure of the behavior of my app. This is the code of one of my tests:

@Test
@DisplayName("GetAfiliations: 5XX Exception")
void getAfiliationsWithError5XX() throws IOException, InternalException {

    ContainerGetExternalAfiliations containerGetExternalAfiliationscontainerGetExternalAfiliations = mapper.readValue(getClass().getClassLoader().getResourceAsStream("jsons/afiliacion.json")
            , ContainerGetExternalAfiliations.class);

    RequestGetAfiliations req = new RequestGetAfiliations();
    req.setDate(LocalDate.now());

    String requestString = mapper.writeValueAsString(req);

    this.server
            .expect(ExpectedCount.once(), requestTo(URL_GET_AFILIATION))
            .andExpect(method(HttpMethod.POST))
            .andExpect(content().contentType(MediaType.APPLICATION_JSON))
            .andExpect(content().json(requestString))
            .andRespond(withStatus(HttpStatus.BAD_GATEWAY));



    Throwable exceptionThatWasThrown = assertThrows(InternalException.class, () -> afiliationsBO.getAfiliations("UID"));
    assertTrue(exceptionThatWasThrown.getMessage().contains("Error handlig external service"));

    this.server.verify();
}

as you can see in the test above I'm only handling a 502 http error but if i'd like to test 500 I'll need another test and for 503 one more and so on.

Anyone knows a way to test every 5XX or 4XX in only one test?

Thanks so much for reading me.

<...>
.andExpect(MockMvcResultMatchers.status().is5xxServerError());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM