Created
April 25, 2019 06:11
-
-
Save farodin91/1e0ab0168e3b6737f51149c74fa90a19 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.junit5test | |
import java.lang.reflect.Method; | |
import java.util.logging.Logger; | |
import org.junit.jupiter.api.extension.*; | |
import org.junit.jupiter.api.extension.ExtensionContext.Namespace; | |
import org.junit.jupiter.api.extension.ExtensionContext.Store; | |
public class TimingExtension implements BeforeEachCallback, BeforeTestExecutionCallback, AfterTestExecutionCallback, AfterEachCallback { | |
private static final Logger logger = Logger.getLogger(TimingExtension.class.getName()); | |
private static final String BEFORE_EACH_TIME = "before each"; | |
private static final String BEFORE_TEST_TIME = "before test"; | |
private static final String AFTER_TEST_TIME = "after test"; | |
@Override | |
public void beforeEach(ExtensionContext context) { | |
getStore(context).put(BEFORE_EACH_TIME, System.currentTimeMillis()); | |
} | |
@Override | |
public void beforeTestExecution(ExtensionContext context) { | |
getStore(context).put(BEFORE_TEST_TIME, System.currentTimeMillis()); | |
} | |
@Override | |
public void afterTestExecution(ExtensionContext context) { | |
getStore(context).put(AFTER_TEST_TIME, System.currentTimeMillis()); | |
} | |
@Override | |
public void afterEach(ExtensionContext context) { | |
Method testMethod = context.getRequiredTestMethod(); | |
long afterEachTime = System.currentTimeMillis(); | |
long beforeEachTime = getStore(context).remove(BEFORE_EACH_TIME, long.class); | |
long beforeTestTime = getStore(context).remove(BEFORE_TEST_TIME, long.class); | |
long afterTestTime = getStore(context).remove(AFTER_TEST_TIME, long.class); | |
long beforeEachDuration = beforeTestTime - beforeEachTime; | |
long testDuration = afterTestTime - beforeTestTime; | |
long afterEachDuration = afterEachTime - afterTestTime; | |
logger.info(() -> | |
String.format("Method [%s] beforeEach %s ms; test %s ms; after %s ms", testMethod.getName(), beforeEachDuration, testDuration, afterEachDuration)); | |
} | |
private Store getStore(ExtensionContext context) { | |
return context.getStore(Namespace.create(getClass(), context.getRequiredTestMethod())); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment