|
| 1 | +package sporadic.customize_annotations_generics_wildcards_examples; |
| 2 | + |
| 3 | +import java.lang.reflect.InvocationTargetException; |
| 4 | +import java.lang.reflect.Method; |
| 5 | +import java.util.List; |
| 6 | + |
| 7 | +public class MyTestRunner { |
| 8 | + public void run(Class<?>... klasses) { |
| 9 | + for (Class<?> testClass : klasses) { |
| 10 | + runTestClass(testClass); |
| 11 | + } |
| 12 | + } |
| 13 | + |
| 14 | + //an overloaded method to the above one, so that it could accept a list of classes, not just a simple array of classes |
| 15 | + public void run(List<Class<?>> testCaseClasses) { |
| 16 | + for (Class<?> testClass : testCaseClasses) { |
| 17 | + runTestClass(testClass); |
| 18 | + } |
| 19 | + } |
| 20 | + |
| 21 | + private void runTestClass(Class<?> klass) { |
| 22 | + for (Method method : klass.getMethods()) { |
| 23 | + SteveSunFirstCustomAnnotation annotation = method |
| 24 | + .getAnnotation(SteveSunFirstCustomAnnotation.class); |
| 25 | + if (annotation != null) |
| 26 | + runTestMethod(klass, method, annotation); |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + private void runTestMethod(Class<?> klass, Method method, |
| 31 | + SteveSunFirstCustomAnnotation annotation) { |
| 32 | + if (annotation.state() != MyTestState.ACTIVE) |
| 33 | + return; |
| 34 | + try { |
| 35 | + System.out.println("Running test: " |
| 36 | + + getTestName(method, annotation)); |
| 37 | + Object testInstance = klass.newInstance(); |
| 38 | + method.invoke(testInstance); |
| 39 | + System.out.println("SUCCESS"); |
| 40 | + } catch (InstantiationException e) { |
| 41 | + System.err.println("FAILED: Failed to instantiate class " |
| 42 | + + klass.getName()); |
| 43 | + } catch (IllegalAccessException e) { |
| 44 | + System.err.println("FAILED: Failed to call test method " |
| 45 | + + method.getName()); |
| 46 | + } catch (InvocationTargetException e) { |
| 47 | + checkThrowable(annotation, e.getCause()); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + private static String getTestName(Method method, |
| 52 | + SteveSunFirstCustomAnnotation annotation) { |
| 53 | + return !annotation.name().isEmpty() ? annotation.name() : method |
| 54 | + .getName(); |
| 55 | + } |
| 56 | + |
| 57 | + private void checkThrowable(SteveSunFirstCustomAnnotation annotation, |
| 58 | + Throwable th) { |
| 59 | + if (annotation.expected() == th.getClass()) |
| 60 | + System.out.println("annotation.expected() executes: SUCCESS"); |
| 61 | + else if (annotation.ignore() == th.getClass()) { |
| 62 | + System.out.println("annotation.ignore() executes: SUCCESS"); |
| 63 | + } else { |
| 64 | + System.out.println("FAILED: " + th.getMessage()); |
| 65 | + } |
| 66 | + } |
| 67 | +} |
0 commit comments