To find the number of test methods in JUnit TestCase

Is there a way to find out the number of test methods in a test case?

What I want to do is to have a test case that tests several scenarios, and for all these I would do data setUp () only once. Similarly, I would like to do a cleanup (tearDown ()) once at the end of all testing methods.

The current approach I use is to maintain a counter of the number of test methods present in the file, and reduce them in the tearDown method and perform a cleanup when the counter reaches 0. But this counter needs to be taken care of every new testing method.

+3
source share
7 answers

, setup/teardown, , , , @BeforeClass @AfterClass.

+5
+4

, , JUnit. - ( , ) API- , "@Test", , "", @Test

public class TestCaseCount {

      private static List<Class> getClasses(String packageName)
          throws ClassNotFoundException, IOException {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        assert classLoader != null;
        String path = packageName.replace('.', '/');
        Enumeration<URL> resources = classLoader.getResources(path);
        List<File> dirs = new ArrayList<File>();
        while (resources.hasMoreElements()) {
          URL resource = resources.nextElement();
          dirs.add(new File(resource.getFile()));
        }

        ArrayList<Class> classes = new ArrayList<Class>();
        for (File directory : dirs) {
          classes.addAll(findClasses(directory, packageName));
        }
        return classes /* .toArray(new Class[classes.size()]) */;
      }

      private static List<Class> findClasses(File directory, String packageName)
          throws ClassNotFoundException {
        List<Class> classes = new ArrayList<Class>();
        if (!directory.exists()) {
          return classes;
        }

        File[] files = directory.listFiles();
        for (File file : files) {
          if (file.isDirectory()) {
            assert !file.getName().contains(".");
            classes.addAll(findClasses(file, packageName + "." + file.getName()));
          } else if (file.getName().endsWith(".class")) {
            classes.add(Class.forName(packageName + '.'
                + file.getName().substring(0, file.getName().length() - 6)));
          }
        }
        return classes;
      }

      public static void main(String args[]) {

        ArrayList<Class> classes = new ArrayList<Class>();

        try {
          // Feature1 Test Cases
          classes.addAll(TestCaseCount.getClasses("mypackage.feature1.tests"));

          // Feature2 Test Cases
          classes.addAll(TestCaseCount.getClasses("mypackage.feature2.tests1"));
          classes.addAll(TestCaseCount.getClasses("mypackage.feature2.tests2"));

          // Feature3 Test Cases
          classes.addAll(TestCaseCount.getClasses("mypackage.feature3.tests"));

        } catch (Exception e) {
          e.printStackTrace();
        }

        int testcaseCount = 0;
        for (Class cl : classes) {
          System.out.println("Test Class Name : " + cl.getName());

          Method[] methods = cl.getDeclaredMethods();

          for (Method method : methods) {
            Annotation[] annotations = method.getDeclaredAnnotations();
            if (annotations.length == 0 && method.getName().startsWith("test")) {
              testcaseCount++;
            } else {
              for (Annotation annotation : annotations) {
                if (annotation.annotationType().toString()
                    .equals("interface org.junit.Test")) {
                  testcaseCount++;
                }
              }
            }
          }
        }
        System.out.println("Total Test Cases " + testcaseCount);
      }
    }
+2

@BeforeClass, @AfterClass @Before.

public class CountTest {
  static int count;

  @BeforeClass
  public static void beforeClass() {
    count = 0;
  }

  @Before
  public void countUp() {
    count++;
  }

  @AfterClass
  public static void printCount() {
    System.out.println(count + " tests.");
  }

  @Test
  public void test1() {
    assertTrue(true);
  }
  // some more tests

, :

5 .

+1

Junit4, , , . , , -

, . junit.extensions.TestSetup. .

0

junit 3 - , . , . , .

, , .

0

Using @Rules on TestWatcher , you can take into account the quantity and many other things, such as the method name, etc. You can override these methods and use.

@Override   
public Statement apply(Statement base, Description description){
    return super.apply(base, description);  
}

@Override   
protected void failed(Throwable e, Description description) {
    failed.add(description);
    LogUtil.error("[FAILED] "+description.getMethodName()+" [Test Failed]"+e.getMessage());
    super.failed(e, description);
}

@Override   
protected void finished(Description description) {      
    LogUtil.info("[FINISHED] "+description.getMethodName());
    super.finished(description);
}

@Override    
protected void skipped(AssumptionViolatedException e,Description description) {
    LogUtil.error("[FAILED] Test Failed due to Assumption Voilation "+e.getMessage());
    super.skipped(e,description);
}

@Override
protected void starting(Description description) {
    LogUtil.info("-----------------------------------------------------------");
    LogUtil.info("[STARTED]  "+description.getMethodName());
    super.starting(description);
}

@Override
protected void succeeded(Description description) { 
    passed.add(description);
    LogUtil.info("[PASSED] "+description.getMethodName());
    super.succeeded(description);
}

In your Junit Testcase Utility

@Rule
public TestRule watcher = new TestWatcherChild();
0
source

Source: https://habr.com/ru/post/1703021/


All Articles