【问题标题】:How to run multiple Groovy unit tests如何运行多个 Groovy 单元测试
【发布时间】:2016-02-04 05:56:08
【问题描述】:

我想将我的 groovy 源文件保存在它们自己的目录中,而测试则在单独的目录中。

我的目录结构如下:

.
├── build
│   └── Messenger.class
├── build.xml
├── ivy.xml
├── lib
├── src
│   └── com
│       └── myapp
│           └── Messenger.groovy
└── test
    └── unit
        ├── AnotherTest.groovy
        └── MessengerTest.groovy

我可以通过使用groovy 命令并使用-cp 指定被测单元的类路径以指向build/ 来成功运行一个测试,但是如何运行目录中的所有测试?

【问题讨论】:

  • 你是如何运行这些测试的?在 Grails 中,test-app 通常会运行所有测试,除非您明确限制它们,所以我假设您使用的是非标准方式?
  • 这不是 Grails 应用程序。
  • 然后去掉grails标签
  • 我有它,因为我使用的是目录结构。

标签: unit-testing testing groovy tdd


【解决方案1】:

你可以使用命令运行所有单元测试:

grails 测试应用单元:

如果您有单元、集成、功能...测试,您可以使用命令运行所有测试:

grails 测试应用

【讨论】:

  • 这不是 Grails 应用程序,我只是在模仿一下目录结构。
  • 我没有使用 IDE,这就是我使用 groovy 命令运行测试的原因。
【解决方案2】:

我是 groovy 的新手,但我编写了自己的测试运行器并将其放在项目的根目录中。源代码:

import groovy.util.GroovyTestSuite
import junit.textui.TestRunner
import junit.framework.TestResult
import static groovy.io.FileType.FILES


public class MyTestRunner {
    public static ArrayList getTestFilesPaths(String test_dir) {
        // gets list of absolute test file paths
        ArrayList testFilesPaths = new ArrayList();

        new File(test_dir).eachFileRecurse(FILES) {
            if(it.name.endsWith(".groovy")) {
                testFilesPaths.add(it.absolutePath)
            }
        }

        return testFilesPaths;
    }

    public static GroovyTestSuite getTestSuite(ArrayList testFilesPaths) {
        // creates test suite using absolute test file paths
        GroovyTestSuite suite = new GroovyTestSuite();
        testFilesPaths.each {
            suite.addTestSuite(suite.compile(it));
        }
        return suite;
    }

    public static void runTests(GroovyTestSuite suite) {
        // runs test in test suite
        TestResult result = TestRunner.run(suite);
        // if tests fail return exit code non equal to 0 indicating that
        // tests fail it helps if one of your build step is to test files
        if (!result.wasSuccessful()) {
            System.exit(1);
        }
    }
}

ArrayList testFilesPaths = MyTestRunner.getTestFilesPaths("tests");
GroovyTestSuite suite = MyTestRunner.getTestSuite(testFilesPaths);
MyTestRunner.runTests(suite)

如果您尝试使用它,请注意如果它失败了,很可能getTestFilesPaths 无法正常工作。

我的目录结构

.
├── test_runner.groovy
├── src
│   └── ...
└── tests
    └── Test1.groovy
    └── someDir
        ├── Test2.groovy
        └── Test3.groovy

如何运行
从运行 test_runner.groovy 的同一目录中:

groovy test_runner.groovy

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多