JAVA/Etc.

TDD 주요 애노테이션 정리 + Assertions 메서드모음 Junit5 기준

새끼코딩오리 2024. 10. 20. 19:58
@Test 테스트 메소드를 정의할 때 사용. 각 테스트는 이 애노테이션으로 표시됨. @Test void exampleTest() { ... }
@BeforeEach 각 테스트 메소드 실행 전에 공통적으로 실행해야 하는 초기화 작업을 정의할 때 사용. @BeforeEach void setup() { ... }
@AfterEach 각 테스트 메소드 실행 후에 정리 작업을 수행할 때 사용. @AfterEach void tearDown() { ... }
@BeforeAll 모든 테스트가 실행되기 전에 한 번 실행되는 메소드를 정의할 때 사용. 정적 메소드로 정의해야 함. @BeforeAll static void initAll() { ... }
@AfterAll 모든 테스트가 실행된 후에 한 번 실행되는 메소드를 정의할 때 사용. 정적 메소드로 정의해야 함. @AfterAll static void tearDownAll() { ... }
@DisplayName 테스트 메소드에 대해 사용자 정의 이름을 지정할 때 사용. @Test @DisplayName("Custom Test Name") void ...
@Disabled 특정 테스트 메소드를 비활성화할 때 사용. 실행되지 않음. @Disabled @Test void disabledTest() { ... }
@Nested 내부 클래스를 테스트 그룹으로 구성하여 테스트할 때 사용. @Nested class InnerTestClass { ... }
@Tag 테스트에 태그를 붙여서 그룹화하거나 필터링할 때 사용. @Tag("fast") @Test void fastTest() { ... }
@ParameterizedTest 매개변수화된 테스트를 정의할 때 사용. 다양한 입력값으로 동일한 테스트를 여러 번 실행할 수 있음. @ParameterizedTest @ValueSource(ints = {1, 2})
@ValueSource @ParameterizedTest와 함께 사용되며, 테스트에 전달할 매개변수 값을 정의. @ValueSource(strings = {"a", "b"})
@CsvSource CSV 형식의 데이터를 @ParameterizedTest에 제공할 때 사용. @CsvSource({"1, 2", "3, 4"})
@MockitoAnnotations Mockito를 사용하여 테스트에서 목(mock) 객체를 초기화할 때 사용. @MockitoAnnotations.initMocks(this);
@ExtendWith JUnit 외부 확장 기능을 사용할 때 사용. @ExtendWith(MockitoExtension.class)
@Mock Mockito를 사용하여 목 객체를 생성할 때 사용. @Mock List<String> mockList;
@InjectMocks Mockito를 사용하여 자동으로 목 객체를 주입할 때 사용. @InjectMocks MyService myService;

 

입력을 대신 받을때는 꼭 close로 닫아줘야한다. 안그럼 꼬임.

 

JUnit 5 - 변수는 여러개 들어갈 수 있으니 IDE에서 잘 확인해볼것.

assertEquals(expected, actual) 두 값이 동일한지 확인. 같지 않으면 테스트 실패. assertEquals(5, sum(2, 3));
assertTrue(condition) 조건이 true인지 확인. false면 테스트 실패. assertTrue(isActive);
assertFalse(condition) 조건이 false인지 확인. true면 테스트 실패. assertFalse(isValid);
assertNotNull(object) 객체가 null이 아닌지 확인. null이면 테스트 실패. assertNotNull(user);
assertNull(object) 객체가 null인지 확인. null이 아니면 테스트 실패. assertNull(result);
assertThrows(expectedType, executable) 특정 예외가 발생하는지 확인. 발생하지 않거나 다른 예외 발생 시 테스트 실패. assertThrows(IllegalArgumentException.class, () -> {...});
assertDoesNotThrow(executable) 실행 중 예외가 발생하지 않는지 확인. 예외 발생 시 테스트 실패. assertDoesNotThrow(() -> someMethod());
assertSame(expected, actual) 두 객체가 동일한 참조를 가리키는지 확인. 그렇지 않으면 테스트 실패. assertSame(expectedObject, actualObject);
assertNotSame(unexpected, actual) 두 객체가 동일한 참조를 가리키지 않는지 확인. 그렇다면 테스트 실패. assertNotSame(obj1, obj2);
assertArrayEquals(expected, actual) 두 배열이 동일한지 확인. 다르면 테스트 실패. assertArrayEquals(new int[]{1, 2}, resultArray);
assertAll(executable...) 여러 assertion을 그룹화해 한 번에 실행. 한 개라도 실패하면 전체 테스트 실패. assertAll(() -> assertEquals(1, val1), () -> assertTrue(val2));
assertTimeout(duration, executable) 주어진 시간 내에 코드가 완료되는지 확인. 시간 초과 시 테스트 실패. assertTimeout(Duration.ofMillis(500), () -> someMethod());
assertTimeoutPreemptively(duration, executable) 주어진 시간 내에 강제 종료 후 예외 발생. assertTimeoutPreemptively(Duration.ofMillis(100), () -> {...});
assertInstanceOf(expectedType, actual) 객체가 특정 클래스의 인스턴스인지 확인. 그렇지 않으면 테스트 실패. assertInstanceOf(String.class, object);
assertIterableEquals(expected, actual) 두 Iterable의 내용이 동일한지 확인. 순서까지 확인하며 같지 않으면 테스트 실패. assertIterableEquals(List.of(1, 2), resultList);
assertLinesMatch(expected, actual) 두 스트림 또는 리스트의 문자열이 동일한지 확인. 정규 표현식을 사용해 패턴 비교 가능. assertLinesMatch(List.of("Line 1", "Line 2"), actualLines);
assertNotEquals(unexpected, actual) 두 값이 같지 않은지 확인. 같으면 테스트 실패. assertNotEquals(5, sum(2, 2));
assertThrowsExactly(expectedType, executable) 정확하게 특정 예외가 발생하는지 확인. 예외의 상속 구조까지 확인하여 다르면 테스트 실패. assertThrowsExactly(IllegalArgumentException.class, () -> {...});
fail(message) 특정 조건에서 강제로 실패를 발생시킬 때 사용. fail("Expected exception not thrown");
assertArrayNotEquals(expected, actual) 두 배열이 같지 않은지 확인. 같으면 테스트 실패. assertArrayNotEquals(new int[]{1, 2}, resultArray);

 

assertAll(String heading, executable...) 여러 assertion을 그룹화하여 실행하고, 그룹에 이름을 지정할 수 있음. 하나라도 실패하면 전체 테스트 실패. assertAll("Group 1", () -> assertEquals(1, val1), ...);
assertIterableNotEquals(expected, actual) 두 Iterable의 내용이 같지 않음을 확인. 같으면 테스트 실패. assertIterableNotEquals(List.of(1, 2), resultList);
assertIterableContains(expected, actual) Iterable이 특정 값을 포함하는지 확인. 포함하지 않으면 테스트 실패. assertIterableContains(expectedList, actual);
assertIterableDoesNotContain(expected, actual) Iterable이 특정 값을 포함하지 않는지 확인. 포함하면 테스트 실패. assertIterableDoesNotContain(expectedList, actual);
assertInstanceOfOrThrow(expectedType, actual) 객체가 예상한 타입이 아니면 예외를 발생시키고, 맞으면 그대로 진행. assertInstanceOfOrThrow(String.class, object);
assertDoesNotThrow(executable, message) 예외가 발생하지 않음을 확인하면서 메시지를 제공. 예외 발생 시 메시지와 함께 테스트 실패. assertDoesNotThrow(() -> someMethod(), "Method should not throw");
assertTrue(condition, message) 조건이 true인지 확인하면서 메시지를 제공. 조건이 false이면 메시지와 함께 테스트 실패. assertTrue(isActive, "Should be active");
assertFalse(condition, message) 조건이 false인지 확인하면서 메시지를 제공. 조건이 true이면 메시지와 함께 테스트 실패. assertFalse(isValid, "Should not be valid");
assertNull(object, message) 객체가 null인지 확인하면서 메시지를 제공. 객체가 null이 아니면 메시지와 함께 테스트 실패. assertNull(result, "Result should be null");
assertNotNull(object, message) 객체가 null이 아닌지 확인하면서 메시지를 제공. 객체가 null이면 메시지와 함께 테스트 실패. assertNotNull(user, "User should not be null");
assertSame(expected, actual, message) 두 객체가 동일한 참조를 가리키는지 확인하면서 메시지를 제공. 참조가 다르면 메시지와 함께 테스트 실패. assertSame(obj1, obj2, "Objects should be same");
assertNotSame(expected, actual, message) 두 객체가 동일한 참조를 가리키지 않는지 확인하면서 메시지를 제공. 참조가 같으면 메시지와 함께 테스트 실패. assertNotSame(obj1, obj2, "Objects should not be same");
assertArrayEquals(expected, actual, message) 두 배열이 동일한지 확인하면서 메시지를 제공. 배열이 다르면 메시지와 함께 테스트 실패. assertArrayEquals(new int[]{1, 2}, resultArray, "Arrays differ");
assertArrayNotEquals(expected, actual, message) 두 배열이 같지 않은지 확인하면서 메시지를 제공. 배열이 같으면 메시지와 함께 테스트 실패. assertArrayNotEquals(new int[]{1, 2}, resultArray, "Arrays should differ");
assertTimeoutPreemptively(duration, executable, message) 지정된 시간 내에 코드를 강제로 종료하고, 메시지와 함께 예외 발생. 시간이 초과되면 즉시 실패. assertTimeoutPreemptively(Duration.ofMillis(100), () -> {...}, "Timed out");
assertNotInstanceOf(unexpectedType, actual) 객체가 예상하지 않은 타입의 인스턴스인지 확인. 예상 타입이면 테스트 실패. assertNotInstanceOf(Integer.class, object);
assertArrayLengthEquals(expectedLength, actualArray) 배열의 길이가 예상한 길이와 같은지 확인. 길이가 다르면 테스트 실패. assertArrayLengthEquals(3, resultArray);
assertArrayLengthNotEquals(expectedLength, actualArray) 배열의 길이가 예상한 길이와 같지 않은지 확인. 길이가 같으면 테스트 실패. assertArrayLengthNotEquals(3, resultArray);
assertStringContains(expectedSubstring, actualString) 문자열에 예상된 부분 문자열이 포함되어 있는지 확인. 포함되지 않으면 테스트 실패. assertStringContains("hello", actualString);
assertStringDoesNotContain(unexpectedSubstring, actualString) 문자열에 포함되지 말아야 할 부분 문자열이 포함되어 있지 않은지 확인. 포함되어 있으면 테스트 실패. assertStringDoesNotContain("error", actualString);