Last active
July 1, 2020 16:43
-
-
Save mcculley/667aeece62c3611fdaf7b268032c27ba 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
import org.junit.jupiter.api.Test; | |
import org.junit.platform.commons.support.AnnotationSupport; | |
import org.junit.platform.commons.support.HierarchyTraversalMode; | |
import java.lang.reflect.Method; | |
import java.lang.reflect.Modifier; | |
import java.util.List; | |
import java.util.logging.Logger; | |
import static org.junit.jupiter.api.Assertions.assertEquals; | |
import static org.junit.jupiter.api.Assertions.assertTrue; | |
import static org.junit.platform.commons.util.ReflectionUtils.returnsVoid; | |
public class TestUtilities { | |
private static final Logger logger = Logger.getLogger(TestUtilities.class.getName()); | |
private TestUtilities() { | |
throw new AssertionError("static utility class is not intended to be instantiated"); | |
} | |
/** | |
* Execute all of the functions and methods in the calling class that are marked with a @Test annotation. This is | |
* intended to be invoked once from a static initializer in a class that defines @Test methods or functions. | |
* | |
* @throws AssertionError if any tests fail | |
*/ | |
public static void runTests() { | |
// Note that this depends on knowing the stack depth. | |
final String callingClass = new Exception().getStackTrace()[1].getClassName(); | |
try { | |
runTests(Class.forName(callingClass)); | |
} catch (final ClassNotFoundException e) { | |
throw new AssertionError(e); | |
} | |
} | |
/** | |
* Execute all of the functions and methods in a class that have a @Test annotation. This is intended to be invoked | |
* once from a static initializer in a class that defines @Test methods or functions. | |
* | |
* @param c the Class to test | |
* @throws AssertionError if any tests fail | |
*/ | |
public static void runTests(final Class c) { | |
logger.fine("executing tests for class " + c.getName()); | |
final List<Method> testMethods = AnnotationSupport.findAnnotatedMethods(c, Test.class, | |
HierarchyTraversalMode.TOP_DOWN); | |
for (final Method method : testMethods) { | |
assertTrue(returnsVoid(method)); | |
assertEquals(0, method.getParameterCount()); | |
logger.fine("executing test " + method); | |
try { | |
final boolean isStatic = Modifier.isStatic(method.getModifiers()); | |
final Object o = isStatic ? null : c.getDeclaredConstructor().newInstance(); | |
method.setAccessible(true); | |
method.invoke(o, null); | |
} catch (final Exception e) { | |
throw new AssertionError(e); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment