ysk(0soo)
Lifealong
ysk(0soo)
전체 방문자
오늘
어제
  • 분류 전체보기 (238)
    • Java (50)
      • whiteship-java-study (11)
      • Java (28)
      • time (6)
    • Spring (68)
      • JPA (15)
      • Spring (1)
      • SpringBoot (1)
      • SpringMVC (6)
      • Spring Security (22)
      • Jdbc (1)
      • RestDocs (14)
      • log (6)
    • Kotlin (3)
    • Web (2)
      • nginx (1)
    • Database (14)
      • MySQL (5)
      • PostgreSQL (1)
      • SQL (1)
      • Redis (4)
    • C, C++ (0)
    • Git (1)
    • Docker (2)
    • Cloud (3)
      • AWS (3)
    • 도서, 강의 (0)
      • t5 (0)
    • 기타 (7)
      • 프로그래밍 (1)
    • 끄적끄적 (0)
    • CS (14)
      • 운영체제(OS) (2)
      • 자료구조(Data Structure) (9)
    • 하루한개 (12)
      • 우아한 테크코스-10분테코톡 (12)
    • 스터디 (12)
      • 클린 아키텍처- 로버트마틴 (2)
      • JPA 프로그래밍 스터디 (10)
    • 테스트 (34)
      • JUnit (19)
      • nGrinder (2)
      • JMeter (0)
    • Infra (3)
    • 프로그래머스 백엔드 데브코스 3기 (0)
    • 디자인 패턴 (3)
    • Issue (4)
    • system (1)
      • grafana (0)
      • Prometheus (0)

블로그 메뉴

  • 홈
  • 태그
  • 방명록
  • github

공지사항

인기 글

태그

  • 동등성
  • tree
  • node exporter basic auth
  • 트랜잭션
  • restdocs enum
  • 정규표현식
  • VirtualThread Springboot
  • 구조화된 동시성
  • nginx basic auth
  • LocalDateTime
  • java
  • AccessDecisionVoter 커스텀
  • scope value
  • AccessDecisionManager
  • 가상 스레드 예외 핸들링
  • junit5
  • 동시성 제어
  • 동일성
  • FilterSecurityInterceptor
  • querydsl
  • 가상 스레드
  • DataJpaTest
  • restdocs custom
  • UserDetailsService
  • 인가(Authorization) 처리
  • jpa
  • mysql
  • nGrinder
  • AuthenticationException
  • StructuredConcorrency

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
ysk(0soo)

Lifealong

테스트/JUnit

Java Collection, List, Array 비교, 검증

2023. 1. 25. 01:19

예제 List

List<String> list1 = Arrays.asList("1", "2", "3", "4");
List<String> list2 = Arrays.asList("1", "2", "3", "4");
List<String> list3 = Arrays.asList("1", "2", "4", "3");

JUnit - Assert

@Test
public void whenTestingForEquality_ShouldBeEqual() throws Exception {
    Assert.assertEquals(list1, list2);
    Assert.assertNotSame(list1, list2);
    Assert.assertNotEquals(list1, list3);
}

AssertJ - Assertions

@Test
public void whenTestingForEquality_ShouldBeEqual() throws Exception {
    assertThat(list1)
      .isEqualTo(list2)
      .isNotEqualTo(list3);

    assertThat(list1.equals(list2)).isTrue();
    assertThat(list1.equals(list3)).isFalse();
}

동일한 요소와 크기의 두 목록 인스턴스가 같은지 비교하는 테스트

List first = Arrays.asList(1, 3, 4, 6, 8);
List second = Arrays.asList(8, 1, 6, 3, 4);
List third = Arrays.asList(1, 3, 3, 6, 6);
@Test
void whenTestingForOrderAgnosticEqualityBothList_ShouldBeEqual() {
    assertThat(first).hasSameElementsAs(second);
}
  • hasSameElementsAs 메서드는 중복 요소는 무시한다.
@Test
void whenTestingForOrderAgnosticEqualityBothList_ShouldNotBeEqual() {
    List a = Arrays.asList("a", "a", "b", "c");
    List b = Arrays.asList("a", "b", "c");
    assertThat(a).hasSameElementsAs(b);
}

이 테스트에서는 요소가 동일하지만 두 목록의 크기가 같지 않지만 중복 항목을 무시하므로 Assertion은 여전히 참이다.

hasSameElementsAs()와 관련된 문제를 극복하기 위해 containsExactlyInAnyOrderElementsOf()를 사용할 수 있다.
이 기능 은 두 목록에 순서에 관계없이 정확히 동일한 요소가 포함되어 있는지 확인한다.

assertThat(a).containsExactlyInAnyOrderElementsOf(b);

AssertArrayEquals

assertArrayEquals 은 예상 배열과 실제 배열이 동일한지 확인.

@Test
public void whenAssertingArraysEquality_thenEqual() {
    char[] expected = { 'J', 'u', 'p', 'i', 't', 'e', 'r' };
    char[] actual = "Jupiter".toCharArray();

    assertArrayEquals(expected, actual, "Arrays should be equal");
}

Apache Commons

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-collections4</artifactId>
    <version>4.4</version>
</dependency>

다음은 CollectionUtils 를 사용한 테스트이eㅏ.

@Test
public void whenTestingForOrderAgnosticEquality_ShouldBeTrueIfEqualOtherwiseFalse() {
    assertTrue(CollectionUtils.isEqualCollection(first, second));
    assertFalse(CollectionUtils.isEqualCollection(first, third));
}

isEqualCollection 메소드는 주어진 컬렉션 이 동일한 [카디널리티](https://simple.wikipedia.org/wiki/Cardinality#:~:text=In mathematics%2C the cardinality of,the same number of elements.) 를 가진 정확히 동일한 요소를 포함하는 경우 true 를 반환한다 .
그렇지 않으면 false 를 반환한다 .

Hamcrest

단일 요소가 컬렉션에 있는지 확인 - hasItem()

import static org.hamcrest.Matchers.*;

public static <T> org.hamcrest.Matcher<java.lang.Iterable<? super T>> hasItem(T item) {
    return IsIterableContaining.hasItem(item);
  }

.

List<String> collection = Lists.newArrayList("ab", "cd", "ef");
assertThat(collection, hasItem("cd"));
assertThat(collection, not(hasItem("zz")));

컬렉션에 여러 요소가 있는지 확인 - hasItems()

List<String> collection = Lists.newArrayList("ab", "cd", "ef");
assertThat(collection, hasItems("cd", "ef"));

컬렉션의 모든 요소 확인

엄격한 순서 (with strict order)

List<String> collection = Lists.newArrayList("ab", "cd", "ef");
assertThat(collection, contains("ab", "cd", "ef"));

순서 상관 없이 (with any order)

List<String> collection = Lists.newArrayList("ab", "cd", "ef");
assertThat(collection, containsInAnyOrder("cd", "ab", "ef"));

컬렉션이 비어있는지 확인

List<String> collection = Lists.newArrayList();
assertThat(collection, empty());

배열이 비어 있는지 확인 (Array Check, Empty Array)

String[] array = new String[] { "ab" };
assertThat(array, not(emptyArray()));

Map이 비어있는지 확인 (Map check, Empty Map)

Map<String, String> collection = Maps.newHashMap();
assertThat(collection, equalTo(Collections.EMPTY_MAP));

Iterable이 비어 있는지 확인

Iterable<String> collection = Lists.newArrayList();
assertThat(collection, emptyIterable());

컬렉션 크기 확인

List<String> collection = Lists.newArrayList("ab", "cd", "ef");
assertThat(collection, hasSize(3));

모든 요소의 상태 확인 (상태 비교)

List<Integer> collection = Lists.newArrayList(15, 20, 25, 30);
assertThat(collection, everyItem(greaterThan(10)));

참조

https://www.baeldung.com/hamcrest-collections-arrays

저작자표시 비영리 (새창열림)

'테스트 > JUnit' 카테고리의 다른 글

Mockito Stub 작성 시 주의 사항  (0) 2023.01.28
Mock vs. Stub vs. Spy  (0) 2023.01.28
@WebMvcTest Security 401 403 응답 해결방법 - csrf  (0) 2023.01.25
Mockito Verify, Mock Object 검증, 호출 횟수 검증  (0) 2023.01.25
MockMvc 테스트시 201 created URI를 검증하는 방법  (0) 2023.01.24
    '테스트/JUnit' 카테고리의 다른 글
    • Mockito Stub 작성 시 주의 사항
    • Mock vs. Stub vs. Spy
    • @WebMvcTest Security 401 403 응답 해결방법 - csrf
    • Mockito Verify, Mock Object 검증, 호출 횟수 검증
    ysk(0soo)
    ysk(0soo)
    백엔드 개발을 좋아합니다. java kotlin spring, infra 에 관심이 많습니다. email : kim206gh@naver.com github : https://github.com/devysk

    티스토리툴바