본문 바로가기
Java

🔎 SoftAssertions의 각 Assertions는 독립적인가?

by sangyunpark99 2024. 7. 16.

SoftAssertions 공식문서에서는 SoftAssertions에 대해 다음과 같이 이야기한다.

Suppose we have a test case and in it we'd like to make numerous assertions. In this case, we're hosting a dinner party and we want to ensure not only that all our guests survive but also that nothing in the mansion has been unduly disturbed

 

비유적인 표현으로 명시되었지만, 개인적으로 다음과 같이 해석했다.

"각 Assertions가 독립적으로 서로 영향을 주지 않는다"

 

정말 Assertions가 독립적으로 서로 영향을 주지 않는지에 대해 실험해보자

 

공식문서 링크 : https://www.javadoc.io/doc/org.assertj/assertj-core/latest/org/assertj/core/api/SoftAssertions.html

 

📌 Assertions.assertThat vs SoftAssertions.assertSoftly

테스트 코드를 작성하는데 사용하는 assertThat 메서드와 비교해보도록 하겠다.

 

Assertions.assertThat으로 작성한 Test

 

두개의 Assertions 전부 Fail한 Test이다.

@Test
    @DisplayName("계좌 이체 내역을 저장합니다.")
    void 계좌_이체_내역을_저장합니다() throws Exception{

        //given
        TransferHistory transferHistory = TransferHistory.builder()
                .withdrawalAccountNumber("0123456789")
                .depositAccountNumber("1234567890")
                .transferAmount(BigDecimal.valueOf(10000))
                .amountAfterWithdrawal(BigDecimal.valueOf(0))
                .amountAfterDeposit(BigDecimal.valueOf(20000))
                .build();

        //when
        TransferHistory savedTransferHistory = transferHistoryRepository.save(transferHistory);

        //then
        Assertions.assertThat(savedTransferHistory.getWithdrawalAccountNumber()).isEqualTo("000000000000");
        Assertions.assertThat(savedTransferHistory.getDepositAccountNumber()).isEqualTo("000000000000000");

    }

 

실행 결과

 

오류 코드를 자세히 보면, 첫번째 Assertions에 대한 FailError만 발생하는 것을 볼 수 있다.

그다음 Assertions은 성공했는지, 실패했는지 알 수 있는 방법이 없다. 이전 Assertions가 성공해야만 성공,실패 여부를 알 수 있는 것이다.

 

📌 SoftAssertions.assertSoftly로 작성한 Test

 

두개의 Assertions 전부 Fail한 Test이다.

@Test
@DisplayName("계좌 이체 내역을 저장합니다.")
void 계좌_이체_내역을_저장합니다() throws Exception{

    //given
    TransferHistory transferHistory = TransferHistory.builder()
            .withdrawalAccountNumber("0123456789")
            .depositAccountNumber("1234567890")
            .transferAmount(BigDecimal.valueOf(10000))
            .amountAfterWithdrawal(BigDecimal.valueOf(0))
            .amountAfterDeposit(BigDecimal.valueOf(20000))
            .build();

    //when
    TransferHistory savedTransferHistory = transferHistoryRepository.save(transferHistory);

    //then
    SoftAssertions.assertSoftly(softAssertions -> {
        softAssertions.assertThat(savedTransferHistory.getWithdrawalAccountNumber()).isEqualTo("000000000000");
        softAssertions.assertThat(savedTransferHistory.getDepositAccountNumber()).isEqualTo("0000000000000");
    });
}

 

실행 결과

 

오류 코드를 자세히 보면, 첫번째 Assertions에 대한 FailError뿐만 아니라 두번째 Assertions에 대한 테스트도 Fail이라는 사실을 알려준다. 모든 Assertions들이 독립적으로 서로 영향을 받지 않아서, 주어진 Assertions 테스트를 전부 수행 할 수 있게 된다.