반응형

JUnit 5 확장 모델

  • JUnit 4의 확장 모델
    • @RunWith(Runner)
    • TestRule
    • MethodRule

 

  • JUnit 5의 확장 모델은 단 하나, Extension

 

  • 확장팩 등록 방법 3가지
    • 선언적인 등록 @ExtendWith

    • 프로그래밍 등록 @RegisterExtension
      • 선언적인 등록 방식으로 확장팩을 사용하면 커스터마이징 할 수 없다.
        • 예) 테스트 메서드마다 THRESHOLD 값을 다르게하여 느린 테스트 판별 기준 변경
      • 직접 인스턴스를 생성하여 기준을 변경할 수 있다.

 

  • 확장팩 만드는 방법
    • 테스트 실행 조건
    • 테스트 인스턴스 팩토리
    • 테스트 인스턴스 후-처리기
    • 테스트 매개변수 리졸버
    • 테스트 라이프사이클 콜백
    • 예외 처리
    • ...

JUnit 5 Extention 예제

FindSlowTestExtension.java

public class FindSlowTestExtension implements BeforeTestExecutionCallback, AfterTestExecutionCallback {

    //private static final long THRESHOLD = 1000L; //1초이상 걸리면 느린테스트로 기준 설정(선언적인 등록 방식)

    private long THRESHOLD;

    public FindSlowTestExtension(long THRESHOLD) {
        this.THRESHOLD = THRESHOLD;
    }

    @Override
    public void beforeTestExecution(ExtensionContext context) throws Exception {
        ExtensionContext.Store store = getStore(context);
        store.put("START_TIME", System.currentTimeMillis());
    }

    @Override
    public void afterTestExecution(ExtensionContext context) throws Exception {
        Method requiredTestMethod = context.getRequiredTestMethod();
        SlowTest annotation = requiredTestMethod.getAnnotation(SlowTest.class);

        String testMethodName = context.getRequiredTestMethod().getName();
        ExtensionContext.Store store = getStore(context);
        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 context) {
        String testClassName = context.getRequiredTestClass().getName();
        String testMethodName = context.getRequiredTestMethod().getName();
        ExtensionContext.Store store = context.getStore(ExtensionContext.Namespace.create(testClassName, testMethodName));
        return store;
    }
}

 

SlowTest 애노테이션이 이미 붙은 테스트 메소드는 1초가 지나도 메시지를 전달하지 않는다.

 

SlowTest 애노테이션이 붙지 않은 테스트 메소드가 1초가 초과하면 느린 테스트로 간주하고 메시지를 전달한다.


반응형

+ Recent posts