더 자바, 애플리케이션을 테스트하는 다양한 방법

Ch01. JUnit5 - JUnit5 확장 모델

webmaster 2022. 1. 4. 19:08
728x90
  • JUnit 4의 확장 모델은 @RunWith(Runner), TestRule, MethodRule.
  • JUnit 5의 확장 모델은 단 하나, Extension.
  • 확장팩 등록 방법
    • public class FindSlowTestExtension implements BeforeTestExecutionCallback, AfterTestExecutionCallback {
      
          private long THRESHOLD = 1000L;
      
          public FindSlowTestExtension(long THRESHOLD) {
              this.THRESHOLD = THRESHOLD;
          }
      
          @Override
          public void afterTestExecution(ExtensionContext extensionContext) throws Exception {
              Method requiredTestMethod = extensionContext.getRequiredTestMethod();
              SlowTest annotation = requiredTestMethod.getAnnotation(SlowTest.class);
      
              String testMethodName = extensionContext.getRequiredTestMethod().getName();
              ExtensionContext.Store store = getStore(extensionContext);
              Long start_time = store.remove("START_TIME", long.class);
              long duration = System.currentTimeMillis() - start_time;
              if(duration > THRESHOLD && annotation == null){
                  System.out.printf("Please consider mark method [%s] with @SlowTest\n",testMethodName);
              }
          }
      
          private ExtensionContext.Store getStore(ExtensionContext extensionContext) {
              String testClassName = extensionContext.getRequiredTestClass().getName();
              String testMethodName = extensionContext.getRequiredTestMethod().getName();
              ExtensionContext.Store store = extensionContext.getStore(ExtensionContext.Namespace.create(testClassName, testMethodName));//데이터를 넣고 뺴기
              return store;
          }
      
          @Override
          public void beforeTestExecution(ExtensionContext extensionContext) throws Exception {
      
              ExtensionContext.Store store = getStore(extensionContext);
              store.put("START_TIME", System.currentTimeMillis());
      
          }
      }​
      해당 클래스 파일을 만들어 확장팩에서 사용할 것
      • 여기서는 @SlowTest 어노테이션이 붙지 않고 1초 이상일 경우 메시지 출력
    • 선언적인 등록 @ExtendWith 
      • 해당 테스트에서 오류 출력
    • 프로그래밍 등록 @RegisterExtension
      • 생성자 주입등 코딩이 가능
    • 자동 등록 자바 ServiceLoader 이용
  • 확장팩 만드는 방법 
    • 테스트 실행 조건 
    • 테스트 인스턴스 팩토리 
    • 테스트 인스턴스 후-처리기 
    • 테스트 매개변수 리졸버 
    • 테스트 라이프사이클 콜백 
    • 예외 처리 

참고 : https://junit.org/junit5/docs/current/user-guide/#extensions

 

JUnit 5 User Guide

Although the JUnit Jupiter programming model and extension model will not support JUnit 4 features such as Rules and Runners natively, it is not expected that source code maintainers will need to update all of their existing tests, test extensions, and cus

junit.org

 

728x90