Spring | RestAssured를 이용한 API 테스트

춤인형의 개발일지·2025년 1월 17일

Spring

목록 보기
6/8

TTD는 내가 코드를 잘 짰는지를 시험할 수 있는 중요한 요소가 된다. API 테스트 또한 보통 postMan을 사용해서 데이터를 보내고, 확인하고 하는 방법으로 진행했다. 하지만 더 쉽고 빠른 방법으로 작성하는 방법이 있다.

RestAssured 를 사용해 API테스트를 짠다.

🤖코드의 구조
보통의 TTD는 given / when / then 으로 구성되어 있다.
API테스트도 마찬가지이다.

  • given().log().all()
  • when
  • then().log().all()

Query string 포함 요청 예시

  • queryParam
RestAssured
        .given().log().all()
        .queryParam("isSale", "true")
        .queryParam("minPrice", "50000")
        .queryParam("maxPrice", "100000")
        .when()
        .get("/products") // 서버로 GET /products 요청
        .then().log().all()
        .statusCode(200); // 요청에 대한 서버 응답의 상태코드가 200인지 검증

Path variable 포함 요청 예시

  • pathParam
RestAssured
        .given().log().all()
        .pathParam("productId", "33")
        .when()
        .get("/products/{productId}") // 서버로 GET /products 요청
        .then().log().all()
        .statusCode(200); // 요청에 대한 서버 응답의 상태코드가 200인지 검증

Request body 포함 요청 예시

  • body
RestAssured.given().log().all()
			  .contentType(ContentType.JSON)
			  .body(new RegisterStudentRequest("doraemon@gmail.com", "도라에몽", "dora123"))
			  .when()
			  .post("/members") // POST /members 요청
			  .then().log().all()
			  .statusCode(200);

응답 요청을 받는 경우

  • extract()
  • as(응답dto.class);
ProductDetailResponse response = RestAssured
        .given().log().all()
        .pathParam("productId", "33")
        .when()
        .get("/products/{productId}") 
        .then().log().all()
        .statusCode(200) 
        .extract()
        .as(ProductDetailResponse.class);

리스트 형태로 요청 받는 경우

  • extract()
  • jsonPath()
  • getList(".", 응답 dto.class);
List<ProductResponse> responses = RestAssured
        .given().log().all()
        .when()
        .get("/products") 
        .then().log().all()
        .statusCode(200)
        .extract()
        .jsonPath()
        .getList(".", ProductResponse.class);

예시들은 전부 하드코딩으로 들어가 있지만, 보통은 응답데이터의 변수를 받아 그 변수를 활용해서 작성해주면 된다.


내가 작성한 API예시 이다.

 @Test
    void 게시판수정테스트() {
        BoardResponse 수정전게시판 = RestAssured
                .given().log().all()
                .contentType(ContentType.JSON) //json형태로 데이터가 주어진다.
                .body(new BoardRequest("지유게시판"))
                .when()
                .post("/boards")
                .then().log().all()
                .statusCode(200)
                .extract()
                .as(BoardResponse.class);

//input 값이 2개 일 때
        BoardResponse 수정후게시판 = RestAssured
                .given().log().all()
                .contentType(ContentType.JSON)
                .body(new BoardRequest("자유게시판"))
                .pathParam("boardId", 수정전게시판.id()) // 하드코딩 x
                .when()
                .put("/boards/{boardId}")
                .then().log().all()
                .statusCode(200)
                .extract()
                .as(BoardResponse.class);

        List<BoardResponse> 게시판리스트 = RestAssured
                .given().log().all()
                .when()
                .get("/boards")
                .then().log().all()
                .statusCode(200)
                .extract()
                .jsonPath()
                .getList(".", BoardResponse.class);

        assertThat(게시판리스트).allMatch(board -> !board.boardName().equals(수정전게시판.boardName()));
        assertThat(게시판리스트).anyMatch(board -> board.boardName().equals(수정후게시판.boardName()));
    }

리스트로 응답데이터를 만들 때는 보통 allMatch / antMatch 를 사용해서 한번 더 검증해줘야 한다.

0개의 댓글