Here we create our own annotation:
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Test {
}
Of course, the annotations don't do anything by themselves. We need a tool to process these annotations:
import java.lang.reflect.*;
public class TestRunner {
public static void runTests(Object obj) {
try {
Class cl = obj.getClass();
for (Method m : cl.getDeclaredMethods()) {
Test t = m.getAnnotation(Test.class);
if (t != null) {
m.invoke(obj, null);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Now we can write our own test cases:
public class UnitTest {
public UnitTest() {
TestRunner.runTests(this);
}
@Test
public void testCase1() {
System.out.println("Test Case 1");
}
@Test
public void testCase2() {
System.out.println("Test Case 2");
}
public static void main(String[] args) {
new UnitTest();
}
}
No comments:
Post a Comment