]>
git.argeo.org Git - lgpl/argeo-commons.git/blob - org.argeo.util/src/org/argeo/util/test/Test.java
1 package org
.argeo
.util
.test
;
3 import java
.lang
.reflect
.Method
;
4 import java
.util
.ArrayList
;
5 import java
.util
.Collections
;
8 import java
.util
.TreeMap
;
10 /** A generic tester based on Java assertions and functional programming. */
12 private Map
<String
, TestStatus
> results
= Collections
.synchronizedSortedMap(new TreeMap
<>());
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
);
31 testStatus
.setPassed();
32 } catch (Exception e
) {
33 testStatus
.setFailed(e
);
35 results
.put(uid
, testStatus
);
40 protected List
<Method
> findMethods(Class
<?
> clss
) {
41 List
<Method
> methods
= new ArrayList
<Method
>();
42 // Method call = getMethod(clss, "call");
46 for (Method method
: clss
.getMethods()) {
47 if (method
.getName().startsWith("test")) {
54 protected Method
getMethod(Class
<?
> clss
, String name
, Class
<?
>... parameterTypes
) {
56 return clss
.getMethod(name
, parameterTypes
);
57 } catch (NoSuchMethodException e
) {
59 } catch (SecurityException e
) {
60 throw new IllegalStateException(e
);
64 public static void main(String
[] args
) {
65 // deal with arguments
67 if (args
.length
< 1) {
68 System
.err
.println(usage());
70 throw new IllegalArgumentException();
75 Test test
= new Test();
77 test
.execute(className
);
78 } catch (Throwable e
) {
82 Map
<String
, TestStatus
> r
= test
.results
;
83 for (String uid
: r
.keySet()) {
84 TestStatus testStatus
= r
.get(uid
);
85 System
.out
.println(testStatus
);
89 public static String
usage() {
90 return "java " + Test
.class.getName() + " [test class name]";