java 查找 JUnit TestCase 中测试方法的数量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/535929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 12:46:48  来源:igfitidea点击:

To find the number of test methods in a JUnit TestCase

javajunit

提问by user18727

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

有没有办法知道测试用例中测试方法的数量?

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

我想要做的是有一个测试用例来测试几个场景,对于所有这些我只会做一次数据 setUp() 。同样,我想在所有测试方法结束时进行一次清理 (tearDown())。

The current approach i am using is to maintain a counter for the number of test methods that are present in the file and decrement them in the tearDown method and do the cleanup when the count reaches 0. But this counter needs to be taken care of whenever new test methods are added.

我目前使用的方法是为文件中存在的测试方法的数量维护一个计数器,并在tearDown 方法中将它们递减,并在计数达到 0 时进行清理。但是无论何时都需要处理这个计数器添加了新的测试方法。

回答by krosenvold

Instead of using setup/teardown you should probably use methods annotated with @BeforeClassand @AfterClass instead.

您可能应该使用用@BeforeClass和@AfterClass注释的方法,而不是使用设置/拆卸 。

回答by Volker Stolz

You can do this through @BeforeClass and @AfterClass in JUnit4: http://junit.org/apidocs/org/junit/BeforeClass.html

您可以通过 JUnit4 中的 @BeforeClass 和 @AfterClass 来做到这一点:http://junit.org/apidocs/org/junit/BeforeClass.html

Volker

沃尔克

回答by MoA

Here is the piece of code I wrote to find all the test cases in my JUnit project. What it does is reads the files(under package mentioned in code) and using reflection APIs, finds the test cases with annotations "@Test" and also the ones which start with "test" but don't have the @Test annotation

这是我编写的一段代码,用于查找 JUnit 项目中的所有测试用例。它所做的是读取文件(在代码中提到的包下)并使用反射API,找到带有注释“@Test”的测试用例以及以“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);
      }
    }

回答by guerda

Short example for counting tests with @BeforeClass, @AfterClassand @Before.

使用@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

Output will be, e.g.:

输出将是,例如:

5 tests.

5 次测试。

回答by SushilG

Using @Ruleson TestWatcheryou can take note of count and many other things like method name etc. You can override these methods and use .

使用@RulesTestWatcher你可以注意到计数和许多其他的事情一样的方法名称等,您可以重写这些方法和使用。

@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 Use

在您的 Junit 测试用例中使用

@Rule
public TestRule watcher = new TestWatcherChild();

回答by Bhushan Bhangale

If you are using Junit4 and the suggestion given by others is the correct one. But if you using earlier version then use this technique to achieve what you want -

如果您使用的是 Junit4 并且其他人给出的建议是正确的。但是,如果您使用早期版本,则使用此技术来实现您想要的 -

You can define a suite for all those tests for which you want to setup and teardown only once. Take a look at junit.extensions.TestSetup class. Instead of executing your test classes you need to then execute these suites.

您可以为所有您只想设置和拆卸一次的测试定义一个套件。看看 junit.extensions.TestSetup 类。您需要执行这些套件,而不是执行您的测试类。

回答by Aaron Digulla

A solution for junit 3 is to call a special setup method in every test which checks a static flag. if the flag is not set, run the global setup. If it is, skip the setup.

junit 3 的一个解决方案是在每个检查静态标志的测试中调用一个特殊的设置方法。如果未设置标志,请运行全局设置。如果是,请跳过设置。

Make sure the global setup is properly synchronized if you want to run tests in parallel.

如果要并行运行测试,请确保全局设置正确同步。