brunch

You can make anything
by writing

C.S.Lewis

by 최창규 Jan 28. 2022

REST-assured

멋진 rest api test library

REST API를 테스트하는 라이브러리 중에서 인기 있는 REST-assured(https://rest-assured.io/)를 소개할까 합니다. Java springboot와도 찰떡으로 호환이 되니 쉽게 사용해 볼 수 있을 거예요.


gradle 설정

dependencies {
    testImplementation("io.rest-assured:rest-assured:3.3.0")
}


Java 테스트 케이스 설정

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
class ControllerTest { 

}


GET 테스트

테스트하고자 하는 url이 /v1/users/1이고, 응답 형태가 { "name": "피터" }라고 가정하면

import io.restassured.RestAssured.*
import org.hamcrest.Matchers.*

@Test
fun method() {

    get("/v1/users/1").
    then().
        statusCode(200).      // 응답 상태 검증
        body("name", equalTo("피터"))   // 응답 바디 검증
}


POST 테스트

요청 Body를 실어서 보낼 수 있습니다.

@Test
fun method() {
    val peter = Person(). apply {
        name = "피터"
    }

     given(). 
        body(peter).
        post("/v1/users").
    then().
        statusCode(201)
}


TIP

1. 응답 바디 출력하기

get("/v1/users"). body(). prettyPrint()

2. 바디를 객체로 변환하기

val peter = get("/v1/users/1"). as(Person::class.java)

3. body에 jsonPath로 검증

// 응답 
{    
    "lotto":{      
         "lottoId":5,
          "winning-numbers":[2,45,34,23,7,5,3],       
          "winners":[
              {
                   "winnerId":23,
                   "numbers":[2,45,34,23,3,5]          
              },         
             {             
                 "winnerId":54,           
                 "numbers":[52,3,12,11,18,22]         
             }      
        ]   
    } 
}

// 테스트 코드
get("/lotto/{id}", 5).
then().             
    body("lotto.winners.winnerId", hasItems(23, 54));

4.hamcrest matcher

then(). body("url", startsWith("https://hairshop.kakao.com/shops")) 
keyword
매거진의 이전글 전체 매장의 수수료 타입을 뽑아 보자.

작품 선택

키워드 선택 0 / 3 0

댓글여부

afliean
브런치는 최신 브라우저에 최적화 되어있습니다. IE chrome safari