如何使用ANT在类或套件中运行所有测试时打印当前正在执行的JUnit测试方法?

时间:2013-03-05 11:16:04

标签: java junit ant junit4

我有一组JUnit测试用例,我使用junit任务从ANT执行它们。在执行测试时,在控制台中我只能看到当前正在运行的测试用例(即Java类),而不是测试方法。有没有办法打印当前正在执行的测试方法?或者除了拥有自己的JUnit测试运行器之外还有其他方法吗?

示例控制台输出

[junit] Running examples.TestCase1
[junit] Tests run: 3, Failures: 0, Errors: 0, Time elapsed: 2.835 sec

相反,我希望得到像

这样的输出
[junit] Running examples.TestCase1
[junit] Running examples.TestCase1.test1
[junit] Running examples.TestCase1.test2
[junit] Running examples.TestCase1.test3
[junit] Tests run: 3, Failures: 0, Errors: 0, Time elapsed: 2.835 sec

6 个答案:

答案 0 :(得分:7)

不幸的是,没有好方法可以挂钩JUnit。对于使用TDD开发的框架,它是令人惊讶的敌意。

改为使用@Rule

import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Log the currently running test.
 * 
 * <p>Typical usage:
 * 
 * <p>{@code @Rule public LogTestName logTestName = new LogTestName();}
 *
 * <p>See also:
 * <br>{@link org.junit.Rule}
 * <br>{@link org.junit.rules.TestWatcher}
 */
public class LogTestName extends TestWatcher {

    private final static Logger log = LoggerFactory.getLogger( "junit.logTestName" );

    @Override
    protected void starting( Description description ) {
        log.debug( "Test {}", description.getMethodName() );
    }

}

注意:

我正在使用静态记录器。这使代码执行得更快,但我的主要原因是记录测试名称是一个贯穿各领域的问题:我想在一个中心位置启用/禁用此日志记录,而不是为每个测试类配置它。

另一个原因是我有处理构建输出的工具,并且更容易配置固定模式: - )

如果您不想这样,那么只需获取description.getTestClass()的记录器。

答案 1 :(得分:1)

您可以尝试使用formatter将type设置为plain。

<formatter type="plain" usefile="false"/>

您可以通过扩展org.apache.tools.ant.taskdefs.optional.junit.JUnitResultFormatter类来使用工具自定义格式化程序。

答案 2 :(得分:0)

如果您不想创建自己的测试运行器,可以尝试使用stacktrace。

以下方法打印调用它的方法的类和方法名称。

public static void printMethod() {
    System.out.println(Thread.currentThread().getStackTrace()[2]);
}

您必须在每个测试方法中调用此方法。

答案 3 :(得分:0)

添加showoutput="true"导致我的junit测试在测试执行时记录输出:

junit fork="yes" showoutput="true" printsummary="withOutAndErr"

答案 4 :(得分:0)

testStarted()派生一个类并覆盖Description方法。它会收到description.getMethodName()参数,您可以从中获取测试类和测试方法 - 例如Intent intent = new Intent(Intent.ACTION_VIEW); Uri uri = [Uri for your folder]; intent.setDataAndType(uri, "image/*"); startActivity(Intent.createChooser(intent, "Open [App] images"));

答案 5 :(得分:0)

您可以使用TestName规则。只需将以下代码添加到测试类中即可:

@Rule
public TestName testName = new TestName();

@Before
public void printTestMethod() {
    System.out.println("Running " + testName.getMethodName());
}
相关问题