get API 를 post 로 요청하거나 그 반대의 경우에 발생한다. 정해진 URL 에 요청한 메소드로 받는 API 가 없어 발생한다.

예시

PathController.java

@RestController
@RequestMapping("/paths")
public class PathController {

    private final PathService pathService;

    public PathController(final PathService pathService) {
        this.pathService = pathService;
    }

    @GetMapping
    public ResponseEntity<PathResponse> showPath(@ModelAttribute @Valid PathRequest pathRequest) {
        final PathResponse pathResponse = pathService.findShortestPath(pathRequest.getSource(), pathRequest.getTarget());
        return ResponseEntity.ok().body(pathResponse);
    }
}

우아한테크코스에서 지하철 경로 조회 미션 중 일부 코드이다. /paths 를 URL 로 받는 API 는 get 밖에 없다.

PathControllerTest.java

@DisplayName("지하철 경로 관련 Controller 테스트")
@WebMvcTest(PathController.class)
class PathControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private PathService pathService;

    @DisplayName("지하철 경로 조회 시 출발역 이름에 null 을 입력하면 예외가 발생한다.")
    @Test
    void createStationBlank() throws Exception {
        // given
        RequestBuilder request = MockMvcRequestBuilders
                .post("/paths") // get 이 아닌 post 로 요청함
                .param("source", "1")
                .param("target", "3")
                .param("age", "-1");

        // when & then
        mockMvc.perform(request)
                .andExpect(status().isBadRequest())
                .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("나이는 1 이상이어야 합니다."));
    }
}

post 로 받는 API 가 정의되어 있지 않으므로 405 예외가 발생하였다.

Untitled