본문 바로가기
멋쟁이사자처럼 동아리/Java

멋쟁이사자처럼 JAVA - AssertThat

by PlusUltraCode 2024. 5. 6.

1. isEqualTo 메소드

assertThat(actual).isEqualTo(expected);

 assertThat(actual).isNotEqualTo(expected);

assertThat(actual).isNull(); => null인지 판별

assertThat(actual).isNotNull();

assertThat(actual).isSameAs(expected);

 assertThat(actual).isNotSameAs(expected);

2. 예외

assertThatThrownBy(() -> {
causeException();
}).isInstanceOf(IllegalCallerException.class)

assertThatThrownBy(() -> {
                causeException();
            }).isInstanceOf(IllegalCallerException.class)
                    .hasMessage("예외가 발생했습니다.");


특정 메세지까지 출력 가능

 assertThatCode(() -> {
                final var number = Integer.valueOf(0x80000000);
            }).doesNotThrowAnyException();

assertThat(actual).contains(expected); 문자열이 포함되어있나여?

assertThat(actual).startsWith(expected); 문자열이 특정 문자열로 시작하나여?

assertThat(actual).endsWith(expected); 문자열이 특정 문자열로 끝나여.

assertThat(actual).matches(expected); 문자열이 정규 표현식과 일치하는지 비교.


assertThat(actual).hasSize(expected); actual 의 크기가 expected인가요?

assertThat(actual).contains(expected); actual 에 expected라는 특정 객체가 포함되어 있나여?


final var actual = List.of(1, 2, 3);
            final var expected = List.of(1, 2, 3);

           assertThat(actual).containsExactlyElementsOf(expected);

이렇게 여러개일 경우또한 객체 비교 가능


[마지막]

 /**
         * `extracting` 메서드는 Collection에 포함된 객체들 중 특정 필드를 추출할 때 사용합니다.
         * <p>
         * `extracting` 메서드는 추출한 필드를 기반으로 메서드를 사용할 수 있습니다.
         * 추출한 필드를 기반으로 메서드를 사용하면 테스트 코드를 작성할 때 더 편리하게 작성할 수 있습니다.
         */
        @Test
        @DisplayName("extracting 메서드로 Collection에 포함된 객체들 중 특정 필드를 추출한다")
        void extracting_메서드로_Collection에_포함된_객체들_중_특정_필드를_추출한다() {
            class User {
                private final String username;
                private final String password;

                User(final String username, final String password) {
                    this.username = username;
                    this.password = password;
                }

                public String getUsername() {
                    return username;
                }
            }

            final var actual = List.of(
                    new User("user1", "password1"),
                    new User("user2", "password2"),
                    new User("user3", "password3")
            );
            final var expected = List.of("user1", "user2", "user3");

            assertThat(actual).extracting("username").containsExactlyElementsOf(expected);

'멋쟁이사자처럼 동아리 > Java' 카테고리의 다른 글

멋쟁이사자처럼 JAVA -JUnit5 문법  (0) 2024.05.06