public class FindSlowTestExtension implements BeforeTestExecutionCallback, AfterTestExecutionCallback {
private final static long THRESHOLD = 1000L;
@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 testMethod = context.getRequiredTestMethod();
SlowTest annotation = testMethod.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();
return context.getStore(ExtensionContext.Namespace.create(testClassName, testMethodName));
}
}
선언 적인 등록 방법
Extension Class 를 선언하여 등록하며, 클래스를 그대로 사용해야 한다. (인수를 넣을 수 없다)
@ExtendWith(FindSlowTestExtension.class)
class StudyTest {
@Test
void test() throws InterruptedException {
Thread.sleep(1005L);
// Please consider mark method [%s] with @SlowTest.
}
}
프로그래밍 등록 방법
Extension Class 를 객체로 생성하기 때문에 생성자 등을 통해서 인수를 넣을 수 있다.
class StudyTest {
@RegisterExtension
static FindSlowTestExtension findSlowTestExtension =
new FindSlowTestExtension(1000L);
@Test
void test() throws InterruptedException {
Thread.sleep(1005L);
// Please consider mark method [%s] with @SlowTest.
}
}