Junit 测试在没有失败跟踪的情况下失败

Junit test to fail without failure trace

我正在 运行 从 Eclipse 进行 JUnit 测试,并在我想要导致测试失败时使用命令 Assert.fail(message)。问题是我总是收到消息以及整个故障跟踪。有什么方法可以让 JUnit 只显示消息而不显示堆栈跟踪?

如果测试抛出错误,测试通常会自动失败而不显示消息。您当然可以捕获异常并让测试在 catch 子句中失败。像这样:

@Test
public void test()  {
   try {
      // your test
  } catch (Exception e) {
      fail("I caught an " + e.class.getSimpleName());
   }
}

当然,在处理异常时,一如既往地尽可能精确地捕获它们。

Eclipse JUnit 设置可通过 Window --> 首选项 --> Java --> Junit 允许针对某些异常切割堆栈跟踪 类:

使用这些设置,测试的堆栈跟踪:

@Test
public void test() {
    fail("Not yet implemented");
}

被过滤:

现在尝试取消选择 "org.junit.*"(或 "junit.framework.Assert",具体取决于您使用的 JUnit 版本),然后重新运行测试。堆栈跟踪立即变得可怕:

也许这就是您正在寻找的功能。

我找到了一种使测试崩溃而不显示长故障痕迹的方法。我没有使用 Assert.fail(),而是创建了自己的异常,并将故障跟踪设置为最小值:

public static void failTest(String message) throws MyTestFailure {
    System.err.println(message);
    MyTestFailure exception = new MyTestFailure(message);
    StackTraceElement elem = new StackTraceElement("com.my.package.Utils", "failTest", "failTest", 3);
    StackTraceElement elem1[] = new StackTraceElement[1];
    elem1[0] = elem;
    exception.setStackTrace(elem1);
    throw exception;
}

这样我只打印我想打印的消息,然后是一行

我会简单地为我的自定义 Throwable 覆盖 printStackTrace() 方法:

  • 异常 -> 错误

  • 断言错误 -> 失败

import java.io.PrintStream;
import java.io.PrintWriter;

public class TestErrorException extends Exception{

    private static final long serialVersionUID = -3486394019411535690L;
    private String message;

    public TestErrorException(String message) {
        this.message = message;
    }

    @Override
    public void printStackTrace() {
        System.err.println(message);
    }

    @Override
    public void printStackTrace(PrintStream s) {
        s.println(message);
    }

    @Override
    public void printStackTrace(PrintWriter s) {
        s.println(message);
    }

}