In this lesson, you completed the final testing of the Create (POST
) operation for the CashCard API and encountered an important learning moment regarding how IDs are handled when creating new resources.
CashCard
was successfully created. You used the URI provided in the Location
response header to retrieve the newly created resource.To deepen your understanding, you added additional test assertions to verify:
id
of the newly created CashCard
is not null.amount
matches the value specified during creation (e.g., 250.00
).assertThat(getResponse.getStatusCode()).isEqualTo(HttpStatus.OK);
DocumentContext documentContext = JsonPath.parse(getResponse.getBody());
Number id = documentContext.read("$.id");
Double amount = documentContext.read("$.amount");
assertThat(id).isNotNull();
assertThat(amount).isEqualTo(250.00);
These assertions confirm that the CashCard
was created with the correct amount
and that an id
was assigned by the database.
Supplying an ID During Creation:
You experimented by updating the test to supply an id
when creating a new CashCard
:
@Test
void shouldCreateANewCashCard() {
CashCard newCashCard = new CashCard(44L, 250.00);
// ...
}
You also modified build.gradle
to enable more detailed test logging:
test {
testLogging {
showStandardStreams = true
}
}
Test Failure Analysis:
Running the tests resulted in a failure with a 500 INTERNAL_SERVER_ERROR
status:
expected: 201 CREATED
but was: 500 INTERNAL_SERVER_ERROR
The error message indicated:
Failed to update entity [CashCard[id=44, amount=250.0]]. Id [44] not found in database.
Understanding the Issue:
id
in the CashCard
object, the cashCardRepository.save()
method interpreted the operation as an update rather than a create.CashCard
with id
44 in the database, the update operation failed.CashCard
instances, you should not provide an id
. The database (via the Repository) is responsible for generating unique IDs.id
changes the operation from a creation to an update, which can lead to errors if the id
does not exist.id
when creating new resources.id
is present in the incoming CashCard
object during a POST
request and returning a 400 BAD REQUEST
status with an appropriate error message if it is.이 레슨에서는 CashCard API의 생성 (POST
) 작업에 대한 최종 테스트를 완료하고, 새 리소스를 생성할 때 ID를 어떻게 처리해야 하는지에 대한 중요한 학습 포인트를 발견했습니다.
CashCard
가 성공적으로 생성되었음을 확인했습니다. 응답의 Location
헤더에 제공된 URI를 사용하여 새로 생성된 리소스를 가져왔습니다.이해를 깊게 하기 위해 추가적인 테스트 단언문을 추가했습니다:
CashCard
의 id
가 null이 아님을 확인합니다.amount
가 생성 시 지정한 값(예: 250.00
)과 일치하는지 확인합니다.assertThat(getResponse.getStatusCode()).isEqualTo(HttpStatus.OK);
DocumentContext documentContext = JsonPath.parse(getResponse.getBody());
Number id = documentContext.read("$.id");
Double amount = documentContext.read("$.amount");
assertThat(id).isNotNull();
assertThat(amount).isEqualTo(250.00);
이 단언문들은 데이터베이스가 id
를 할당했고, amount
가 정확하게 설정되었음을 확인합니다.