This lesson focuses on implementing sorting in a Spring Boot application to return Cash Cards in a meaningful order—specifically, sorting them by amount in descending order. The process involves writing a test that initially fails due to the lack of sorting implementation, adding the sorting functionality in the controller, and then verifying that the tests pass. Additionally, an experiment is conducted by changing the sort order to ensure the robustness of the test.
Key Steps and Concepts:
Writing a Test That Expects Sorted Results:
shouldReturnASortedPageOfCashCards
is added to CashCardApplicationTests
./cashcards?page=0&size=1&sort=amount,desc
, requesting the first page with one Cash Card, sorted by amount in descending order.@Test
void shouldReturnASortedPageOfCashCards() {
ResponseEntity<String> response = restTemplate.getForEntity("/cashcards?page=0&size=1&sort=amount,desc", String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
DocumentContext documentContext = JsonPath.parse(response.getBody());
JSONArray read = documentContext.read("$[*]");
assertThat(read.size()).isEqualTo(1);
double amount = documentContext.read("$[0].amount");
assertThat(amount).isEqualTo(150.00);
}
Understanding the Test:
page=0
: Requests the first page (page indexes start at 0).size=1
: Each page contains one item.sort=amount,desc
: Sorts the results by the amount
field in descending order.Running the Test and Observing Failure:
The test fails with an AssertionFailedError
:
expected: 150.0
but was: 123.45
This means the test expected $150.00 but received $123.45.
The failure occurs because sorting is not yet implemented in the controller; the results are returned in the database's default order.
Implementing Sorting in the Controller:
Sorting is added by modifying the PageRequest.of()
call in CashCardController
to include sorting parameters:
PageRequest.of(
pageable.getPageNumber(),
pageable.getPageSize(),
pageable.getSort()
));
pageable.getSort()
extracts the sort
query parameter from the request URI.
This allows the controller to handle sorting based on the client's request.
Rerunning the Tests:
After implementing sorting, running the tests again shows that all tests pass successfully.
CashCardApplicationTests > shouldReturnAllCashCardsWhenListIsRequested() PASSED
Experimenting by Changing the Sort Order:
To validate the test's robustness, the sort order in the test is changed from descending to ascending:
ResponseEntity<String> response = restTemplate.getForEntity("/cashcards?page=0&size=1&sort=amount,asc", String.class);
The test is expected to fail because the smallest amount ($1.00) should now be returned first.
Running the tests results in a failure, as expected:
CashCardApplicationTests > shouldReturnASortedPageOfCashCards() FAILED
org.opentest4j.AssertionFailedError:
expected: 150.0
but was: 1.0
This failure confirms that the sorting functionality works correctly and the test is effective.
Restoring the Test to Pass:
sort=amount,desc
) to ensure that the test passes again.Conclusion:
sort
in the controller is essential for building flexible APIs.이 강의는 Spring Boot 애플리케이션에서 정렬을 구현하여 Cash Card를 의미 있는 순서로 반환하는 방법에 초점을 맞추고 있습니다. 특히 금액을 기준으로 내림차순 정렬하여 가장 높은 금액이 먼저 오도록 합니다. 먼저 실패하는 테스트를 작성하고, 컨트롤러에 정렬 기능을 구현한 후, 테스트가 통과하는지 확인합니다. 또한, 테스트의 견고성을 확인하기 위해 정렬 순서를 변경하는 실험도 수행합니다.
주요 단계 및 개념:
정렬된 결과를 기대하는 테스트 작성:
CashCardApplicationTests
에 새로운 테스트 메소드 shouldReturnASortedPageOfCashCards
를 추가합니다./cashcards?page=0&size=1&sort=amount,desc
로 GET 요청을 보내며, 금액을 기준으로 내림차순 정렬된 첫 번째 페이지의 Cash Card를 요청합니다.@Test
void shouldReturnASortedPageOfCashCards() {
ResponseEntity<String> response = restTemplate.getForEntity("/cashcards?page=0&size=1&sort=amount,desc", String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
DocumentContext documentContext = JsonPath.parse(response.getBody());
JSONArray read = documentContext.read("$[*]");
assertThat(read.size()).isEqualTo(1);
double amount = documentContext.read("$[0].amount");
assertThat(amount).isEqualTo(150.00);
}
테스트 이해하기:
page=0
: 첫 번째 페이지를 요청합니다 (페이지 인덱스는 0부터 시작).size=1
: 페이지당 하나의 아이템을 포함합니다.sort=amount,desc
: amount
필드를 기준으로 내림차순 정렬합니다.테스트 실행 및 실패 관찰:
테스트는 AssertionFailedError
로 실패합니다:
expected: 150.0
but was: 123.45
이는 $150.00을 기대했지만 $123.45를 받았음을 의미합니다.
컨트롤러에 정렬이 아직 구현되지 않아 데이터베이스의 기본 순서대로 결과가 반환되었기 때문입니다.