]> git.argeo.org Git - lgpl/argeo-commons.git/blob - org.argeo.util/src/org/argeo/util/test/Test.java
Use renamed Maven Argeo OSGi plugin.
[lgpl/argeo-commons.git] / org.argeo.util / src / org / argeo / util / test / Test.java
1 package org.argeo.util.test;
2
3 import java.lang.reflect.Method;
4 import java.util.ArrayList;
5 import java.util.Collections;
6 import java.util.List;
7 import java.util.Map;
8 import java.util.TreeMap;
9
10 /** A generic tester based on Java assertions and functional programming. */
11 public class Test {
12 private Map<String, TestStatus> results = Collections.synchronizedSortedMap(new TreeMap<>());
13
14 protected void execute(String className) throws Throwable {
15 ClassLoader classLoader = Test.class.getClassLoader();
16 Class<?> clss = classLoader.loadClass(className);
17 boolean assertionsEnabled = clss.desiredAssertionStatus();
18 if (!assertionsEnabled)
19 throw new IllegalStateException("Test runner " + getClass().getName()
20 + " requires Java assertions to be enabled. Call the JVM with the -ea argument.");
21 Object obj = clss.getDeclaredConstructor().newInstance();
22 List<Method> methods = findMethods(clss);
23 if (methods.size() == 0)
24 throw new IllegalArgumentException("No test method found in " + clss);
25 // TODO make order more predictable?
26 for (Method method : methods) {
27 String uid = method.getDeclaringClass().getName() + "#" + method.getName();
28 TestStatus testStatus = new TestStatus(uid);
29 try {
30 method.invoke(obj);
31 testStatus.setPassed();
32 } catch (Exception e) {
33 testStatus.setFailed(e);
34 } finally {
35 results.put(uid, testStatus);
36 }
37 }
38 }
39
40 protected List<Method> findMethods(Class<?> clss) {
41 List<Method> methods = new ArrayList<Method>();
42 // Method call = getMethod(clss, "call");
43 // if (call != null)
44 // methods.add(call);
45 //
46 for (Method method : clss.getMethods()) {
47 if (method.getName().startsWith("test")) {
48 methods.add(method);
49 }
50 }
51 return methods;
52 }
53
54 protected Method getMethod(Class<?> clss, String name, Class<?>... parameterTypes) {
55 try {
56 return clss.getMethod(name, parameterTypes);
57 } catch (NoSuchMethodException e) {
58 return null;
59 } catch (SecurityException e) {
60 throw new IllegalStateException(e);
61 }
62 }
63
64 public static void main(String[] args) {
65 // deal with arguments
66 String className;
67 if (args.length < 1) {
68 System.err.println(usage());
69 System.exit(1);
70 throw new IllegalArgumentException();
71 } else {
72 className = args[0];
73 }
74
75 Test test = new Test();
76 try {
77 test.execute(className);
78 } catch (Throwable e) {
79 e.printStackTrace();
80 }
81
82 Map<String, TestStatus> r = test.results;
83 for (String uid : r.keySet()) {
84 TestStatus testStatus = r.get(uid);
85 System.out.println(testStatus);
86 }
87 }
88
89 public static String usage() {
90 return "java " + Test.class.getName() + " [test class name]";
91
92 }
93 }