자바와 JUnit을 활용한 실용주의 단위 테스트 (3)

아연·2023년 10월 14일

Book

목록 보기
4/8
post-thumbnail

<자바와 JUnit을 활용한 실용주의 단위 테스트> 책과 Junit 5, AssertJ 공식문서를 참고하였습니다.



📍 Assert

  1. 참 비교

    • JUnit 5
    assertTrue(boolean condition)
    • AssertJ
    assertThat(boolean condition).isTrue()

  1. 거짓 비교

    • JUnit 5
    assertFalse(boolean condition)
    • AssertJ
    assertThat(boolean condition).isFalse()

  1. 명확한 값 비교

    • JUnit 5
    assertEquals(T actual, T expected)
    • AssertJ
    assertThat(T actual).isEqualTo(T expected)
    • JUnit 5
    assertNotEquals(T actual, T expected)
    • AssertJ
    assertThat(T actual).isNotEqualTo(T expected)

  1. Null 비교

    • JUnit 5
    assertNull(Object actual)
    • AssertJ
    assertThat(T actual).isNull()
    • JUnit 5
    assertNotNull(Object actual)
    • AssertJ
    assertThat(T actual).isNotNull()

  1. 부동 소수점 수 두 개 비교

    • JUnit5 ( 추가 )
      주어진 음수가 아닌 delta 내에서 예상값과 실제값이 같다고 가정합니다.

      public static void assertEquals(double expected, double actual, **double delta**)
    • AssertJ

      SELF isCloseTo(ACTUAL expected, Offset<ACTUAL> offset)
      • Example with double
       // 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:

ParameterDescription
expectedthe given number to compare the actual value to.
offsetthe given positive offset.

Returns:this assertion object.

Throws:

ThrowDescription
NullPointerException if the given offset is null.
NullPointerException if the expected number is null.
AssertionErrorif the actual value is not close to the given one.


📍 Exception

  1. 어노테이션 사용

    • JUnit4
    @Test(expected=InsufficientFoundsException.class)
    • JUnit5
    public static <T extends Throwable> T assertThrows(Class<T> expectedType, Executable executable)

Executable

ExecutableThrowable 을 던질 수 있는 모든 일반 코드 블록을 구현하는 데 사용할 수 있는 함수형 인터페이스입니다.

  • Example
@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);
}

  1. try/catch와 fail
try { 
		account.withdraw(100); 
		fail();
} catch (InsufficientFundsException expected) {
		assertEquals(expected.getMessage(), "balance only 0");
}
  • JUnit5 Assertions.class
public static <V> V fail()

  1. ExpectedException

Junit 5 에서 @RuleExpectedException 은 더이상 지원하지 않는다 ^^..!!

@Rule and @ClassRule no longer exist; superseded by @ExtendWith and @RegisterExtension.

@Test(expected = …) and the ExpectedException rule no longer exist; use Assertions.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 보다 먼저 등록됩니다.

0개의 댓글