JUnit 어설션에서의 어레이 비교, 간결한 임베디드 방식
JUnit의 2개의 같은 타입의 어레이에 대해 동일 어소시에이션을 실시하는 간결한 빌트인 방법이 있습니까?디폴트로는 (적어도 JUnit 4에서는) 어레이 오브젝트 자체를 인스턴스 비교하고 있는 것 같습니다.
EG, 작동하지 않음:
int[] expectedResult = new int[] { 116800, 116800 };
int[] result = new GraphixMask().sortedAreas(rectangles);
assertEquals(expectedResult, result);
물론 다음을 사용하여 수동으로 작업을 수행할 수 있습니다.
assertEquals(expectedResult.length, result.length);
for (int i = 0; i < expectedResult.length; i++)
assertEquals("mismatch at " + i, expectedResult[i], result[i]);
하지만 더 좋은 방법은 없을까?
org.junit을 사용합니다.아사트의 방법assertArrayEquals
:
import org.junit.Assert;
...
Assert.assertArrayEquals( expectedResult, result );
이 메서드를 사용할 수 없는 경우 Assert 클래스를 실수로 Import했을 수 있습니다.junit.framework
.
사용할 수 있습니다.Arrays.equals(..)
:
assertTrue(Arrays.equals(expectedResult, result));
어레이를 문자열로 변환하는 것을 선호합니다.
Assert.assertEquals(
Arrays.toString(values),
Arrays.toString(new int[] { 7, 8, 9, 3 }));
이렇게 하면 잘못된 값이 어디에 있는지 확실히 알 수 있습니다.이 방법은 소규모 어레이에서만 유효하게 동작하지만 유닛 테스트에서는 7개 이상의 아이템을 가진 어레이는 거의 사용하지 않습니다.
이 방법은 기본 유형 및 오버로드 시 다른 유형에 대해 작동합니다.toString
는 모든 필수 정보를 반환합니다.
Assert.assertArrayEquals("message", expectedResult, result)
JUnit 5에서는 Assertions를 Import하여 Assertions.assertArrayEquals 메서드를 사용할 수 있습니다.
import org.junit.jupiter.api.Assertions;
Assertions.assertArrayEquals(resultArray,actualResult);
junit4와 Hamcrest를 사용하면 어레이를 쉽게 비교할 수 있습니다.또, 에러 트레이스내의 에러의 상세한 것에 대해서도 설명합니다.
import static org.junit.Assert.*
import static org.hamcrest.CoreMatchers.*;
//...
assertThat(result, is(new int[] {56, 100, 2000}));
장애 추적 출력:
java.lang.AssertionError:
Expected: is [<56>, <100>, <2000>]
but: was [<55>, <100>, <2000>]
JUnit4에 대한 질문인 것은 알지만 JUnit3에 갇힌 경우 다음과 같은 짧은 유틸리티 함수를 만들 수 있습니다.
private void assertArrayEquals(Object[] esperado, Object[] real) {
assertEquals(Arrays.asList(esperado), Arrays.asList(real));
}
JUnit3에서는 어레이를 직접 비교하는 것보다 이 방법이 더 좋습니다.왜냐하면 어떤 요소가 다른지 자세히 알 수 있기 때문입니다.
org.junit의 클래스 아사션.jupiter.api
용도:
public static void assertArrayEquals(int[] expected,
int[] actual)
언급URL : https://stackoverflow.com/questions/4228161/comparing-arrays-in-junit-assertions-concise-built-in-way
'programing' 카테고리의 다른 글
VueJ: http 응답 데이터를 캐시하는 최선의 방법 (0) | 2022.08.13 |
---|---|
Vue.js. 자 컴포넌트에 동적으로 변경되는 데이터 전달 (0) | 2022.08.13 |
Vuex에서 재사용 가능한 작업 가져오기 (0) | 2022.08.13 |
Axios에서 VUE JS 데이터 액세스 (0) | 2022.08.13 |
@keyup 이벤트에 의해 이 메서드가 트리거되지 않는 이유는 무엇입니까? (0) | 2022.08.13 |