복붙노트

[SPRING] MockMVC 동일한 테스트 케이스에서 예외 및 응답 코드 테스트 방법

SPRING

MockMVC 동일한 테스트 케이스에서 예외 및 응답 코드 테스트 방법

예외가 발생하고 서버가 500 내부 서버 오류를 반환한다고 주장하고 싶습니다.

인 텐트를 강조 표시하기 위해 코드 스 니펫이 제공됩니다.

thrown.expect(NestedServletException.class);
this.mockMvc.perform(post("/account")
            .contentType(MediaType.APPLICATION_JSON)
            .content(requestString))
            .andExpect(status().isInternalServerError());

물론 isInternalServerError 또는 isOk를 쓰면 문제가되지 않습니다. 예외가 throw.except 문 아래에 throw되는 경우에도 테스트가 통과합니다.

어떻게이 문제를 해결할 수 있습니까?

해결법

  1. ==============================

    1.당신은 아래와 같이 뭔가를 시도 할 수 있습니다 -

    당신은 아래와 같이 뭔가를 시도 할 수 있습니다 -

    추신 : 귀하의 요구 사항에 따라 사용자 정의 할 수있는 일반적인 의사 코드를 제공했습니다.

  2. ==============================

    2.귀하의 컨트롤러 :

    귀하의 컨트롤러 :

    throw new Exception("Athlete with same username already exists...");
    

    귀하의 테스트 :

        try {
            mockMvc.perform(post("/api/athlete").contentType(contentType).
                    content(TestUtil.convertObjectToJsonBytes(wAthleteFTP)))
                    .andExpect(status().isInternalServerError())
                    .andExpect(content().string("Athlete with same username already exists..."))
                    .andDo(print());
        } catch (Exception e){
            //sink it
        }
    
  3. from https://stackoverflow.com/questions/16605811/mockmvc-how-to-test-exception-and-response-code-in-the-same-test-case by cc-by-sa and MIT license