Here the Interface with two methods to be implemented on the next class. this methods will be logged.
@TestInstance(TestInstance.Lifecycle.PER_CLASS) public interface InterfaceLoggedTest { static Logger logger = LogManager.getLogger(InterfaceLoggedTest.class.getName()); @BeforeAll
default void beforeAllTest() { logger.info("Antes que todas las pruebas");
} @AfterAll
default void afterAllTest() { logger.info("Despues de todas las pruebas");
} @BeforeEach
default void beforeEachTest( TestInfo testInfo){ logger.info( () -> String.format("antes de %s", testInfo.getDisplayName()));
} @AfterEach
default void afterEachTest( TestInfo testInfo) { logger.info( ()-> String.format("despues de %s", testInfo.getDisplayName()));
}
void thisMethodIsLoggedByInterface();
void alsoLoggedByInterface(); }
Class that implement de Interface which is logged.
public class ImplementsInterfaceLoggedTest implements InterfaceLoggedTest{ @Override
@Test
public void thisMethodIsLoggedByInterface() { assertTrue( Boolean.TRUE);
} @Override
@Test
public void alsoLoggedByInterface() { assertTrue( Boolean.TRUE);
}
}
Run the Test, the log file generated by log4j2.
17:40:36.082| INFO | InterfaceLoggedTest | Antes que todas las pruebas 17:40:36.091| INFO | InterfaceLoggedTest | antes de thisMethodIsLoggedByInterface() 17:40:36.096| INFO | InterfaceLoggedTest | despues de thisMethodIsLoggedByInterface() 17:40:36.100| INFO | InterfaceLoggedTest | antes de alsoLoggedByInterface() 17:40:36.101| INFO | InterfaceLoggedTest | despues de alsoLoggedByInterface() 17:40:36.102| INFO | InterfaceLoggedTest | Despues de todas las pruebas
TimingExtension
public class TimingExtension implements BeforeTestExecutionCallback,
AfterTestExecutionCallback { private static final Logger logger = LogManager.getLogger(TimingExtension.class);
private static final String START_TIME = "start time";
@Override
public void beforeTestExecution(ExtensionContext context) throws Exception { getStore(context).put( START_TIME, System.currentTimeMillis());
} @Override
public void afterTestExecution(ExtensionContext context) throws Exception { Method method = context.getRequiredTestMethod();
long startTime = getStore(context).remove(START_TIME, long.class);
long duration = System.currentTimeMillis() - startTime; logger.info(()-> String.format("metodo [%s] tiempo %s ms.", method.getName(), duration));
} private Store getStore(ExtensionContext context){ return context.getStore( Namespace.create( getClass(), context.getRequiredTestMethod()));
} }
The class test is extended with @ExtendWith
@ExtendWith(TimingExtension.class) public class TimingExtensionTest { @Test void sleep25ms() throws InterruptedException { Thread.sleep(25); } @Test void sleep50ms() throws InterruptedException { Thread.sleep(50); } }
The Log file
20:13:04.987| INFO | TimingExtension | metodo [sleep25ms] tiempo 32 ms. 20:13:05.045| INFO | TimingExtension | metodo [sleep50ms] tiempo 51 ms.
eot
No hay comentarios:
Publicar un comentario