<자바와 JUnit을 활용한 실용주의 단위 테스트> 책과 Junit 5, AssertJ 공식문서를 참고하였습니다.
참 비교
assertTrue(boolean condition)
assertThat(boolean condition).isTrue()
거짓 비교
assertFalse(boolean condition)
assertThat(boolean condition).isFalse()
명확한 값 비교
assertEquals(T actual, T expected)
assertThat(T actual).isEqualTo(T expected)
assertNotEquals(T actual, T expected)
assertThat(T actual).isNotEqualTo(T expected)
Null 비교
assertNull(Object actual)
assertThat(T actual).isNull()
assertNotNull(Object actual)
assertThat(T actual).isNotNull()
부동 소수점 수 두 개 비교
JUnit5 ( 추가 )
주어진 음수가 아닌 delta 내에서 예상값과 실제값이 같다고 가정합니다.
public static void assertEquals(double expected, double actual, **double delta**)
AssertJ
SELF isCloseTo(ACTUAL expected, Offset<ACTUAL> offset)
// assertions will pass:
assertThat(8.1).isCloseTo(8.0, within(0.2));
// you can use offset if you prefer
assertThat(8.1).isCloseTo(8.0, offset(0.2));
// if difference is exactly equals to the offset (0.1), it's ok
assertThat(8.1).isCloseTo(8.0, within(0.1));
// assertion will fail
assertThat(8.1).isCloseTo(8.0, within(0.01));
Parameters:
| Parameter | Description |
|---|---|
| expected | the given number to compare the actual value to. |
| offset | the given positive offset. |
Returns:this assertion object.
Throws:
| Throw | Description |
|---|---|
| NullPointerException | if the given offset is null. |
| NullPointerException | if the expected number is null. |
| AssertionError | if the actual value is not close to the given one. |
어노테이션 사용
@Test(expected=InsufficientFoundsException.class)
public static <T extends Throwable> T assertThrows(Class<T> expectedType, Executable executable)
Executable 은 Throwable 을 던질 수 있는 모든 일반 코드 블록을 구현하는 데 사용할 수 있는 함수형 인터페이스입니다.
@Test
void exceptionTesting() {
Exception exception = assertThrows(ArithmeticException.class, () -> calculator.divide(1, 0));
assertEquals("/ by zero", exception.getMessage());
}
@Test
void throwsExceptionWhenPopped() {
assertThrows(EmptyStackException.class, stack::pop);
}
try {
account.withdraw(100);
fail();
} catch (InsufficientFundsException expected) {
assertEquals(expected.getMessage(), "balance only 0");
}
Assertions.classpublic static <V> V fail()
Junit 5 에서 @Rule 과 ExpectedException 은 더이상 지원하지 않는다 ^^..!!
@Ruleand@ClassRuleno longer exist; superseded by@ExtendWithand@RegisterExtension.
@Test(expected = …)and theExpectedExceptionrule no longer exist; useAssertions.assertThrows(…)instead.
그래도 @ExtendWith 에 대해 찾아봤으니 정리해보겠다.
@Target({TYPE, METHOD, FIELD, PARAMETER})
@Retention(RUNTIME)
@Documented
@Inherited
@Repeatable(Extensions.class)
@API(status=STABLE, since="5.0")
public @interface ExtendWith
@ExtendWith 는 주석이 달린 테스트 클래스, 테스트 인터페이스, 테스트 메서드, 매개변수 또는 필드에 대한 확장을 등록하는 데 사용되는 반복 가능한 어노테이션입니다.@ExtendWith가 있는 경우 해당 확장은 @ExtendWith 어노테이션이 발견되는 순서대로 등록됩니다.@ExtendWith(A.class) 어노테이션이 있고 그다음에 @ExtendWith(B.class) 어노테이션이 있는 경우, 확장자 A 가 확장자 B 보다 먼저 등록됩니다.