Search code examples
junitjunit4junit-runner

JUnit 4 API Get Handle to a @Test Method


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.


Solution

  • 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