1

Using JUnit 4 API, is there a way to get a handle to a method in a test class that are annotated with @Test?

Here's what I am currently doing:

JUnitCore core = new JUnitCore();
Request request = Request.aClass(MyTest.class);
Result result = core.run(request);
if(result.wasSuccessful())
    System.out.println("SUCCESS"); // or do something else

This code will run all tests in MyTest. However, what I want is to just specify the test class name at the beginning (MyTest.class) and do following in a loop:

  • Get next @Test annotated test in the class.
  • Print details
  • Run the test (possibly using Request.method(MyTest.class, "myTestMethod")

I can perhaps use reflection to get the method names and check if they are annotated with Test, but wanted to see if the JUnit API already provides this functionality.

Kesh
  • 1,077
  • 2
  • 11
  • 20

1 Answers1

1

You can use TestClass:

public void runTests(Class<?> clazz) {
  TestClass testClass = new TestClass(MyTest.class);
  List<FrameworkMethod> tests = testClass.getAnnotatedMethods(
      Test.class);
  for (FrameworkMethod m : tests) {
    String methodName = m.getName();
    Request request = Request.method(clazz, methodName);
    JUnitCore core = new JUnitCore();
    Result result = core.run(request);
    if (result.wasSuccessful())
      System.out.println(m + ": SUCCESS");
    }
  }
}

Note that this is an inefficient way to run tests, especially if you have class rules or you use @BeforeClass or @AfterClass

NamshubWriter
  • 23,549
  • 2
  • 41
  • 59
  • Perfect! just what I was looking for. I am actually exploring load testing my junits with Grinder and unfortunately, running each test separately is the only way I can get their details and report on them individually. Thanks. – Kesh Jul 14 '15 at 14:17
  • @HP Your welcome. You can also use `Request.filter)()` – NamshubWriter Jul 14 '15 at 15:19