Monday 30 June 2014

Simple Testing tool using Annotations

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Test { }

public class TestClass {
    @Test public static void m1() { }
  
    public static void m2() { }
  
    @Test public static void m3() {
        throw new RuntimeException("Boom");
    }
  
    public static void m4() { }
  
    @Test public static void m5() { }
  
    public static void m6() { }
  
    @Test public static void m7() {
        throw new RuntimeException("Crash");
    }
  
    public static void m8() { }
}

import java.lang.reflect.*;

public class RunTests {
   public static void main(String[] args) throws Exception {
      int passed = 0, failed = 0;
      for (Method m : Class.forName(args[0]).getMethods()) {
         if (m.isAnnotationPresent(Test.class)) {
            try {
               m.invoke(null);
               passed++;
            } catch (Throwable ex) {
               System.out.printf("Test %s failed: %s %n", m, ex.getCause());
               failed++;
            }
         }
      }
      System.out.printf("Passed: %d, Failed %d%n", passed, failed);
   }
}

Compile all the java files.

Run the below command

java RunTests TestClass

Output
Test public static void TestClass.m3() failed: java.lang.RuntimeException: Boom

Test public static void TestClass.m7() failed: java.lang.RuntimeException: Crash

Passed: 2, Failed 2


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment