JUnit 中的失败和错误有什么区别?

发布于 2024-09-13 09:16:07 字数 62 浏览 4 评论 0原文

我在大型代码库上运行 JUnit 测试,并且我已经意识到有时会收到“错误”,而有时会收到“失败”。有什么区别?

I'm running JUnit tests on a large code base, and I've been realizing that sometimes I get "Errors" while other times I get "Failures". What's the difference?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

ら栖息 2024-09-20 09:16:07

失败当你的测试用例失败时——即你的断言不正确。

错误发生意外错误/异常时 - 即在尝试实际运行测试时抛出意外异常,如 FileNotFound 等。

Failures are when your test cases fail – i.e. your assertions are incorrect.

Errors are when unexpected errors/exceptions occur - i.e. while trying to actually run the test and an unexpected exception is thrown like FileNotFound, etc`.

靖瑶 2024-09-20 09:16:07

如果您的测试抛出异常,但该异常未通过 Junit 中的断言框架向上冒泡,则会将其报告为错误。比如NullPointer,或者ClassNotFound异常会报错:

String s = null;
s.trim();

或者,

try {

    // your code
} catch(Exception e) {
    // log the exception
    throw new MyException(e);
}

话虽如此,下面会报错:

Assert.fail("Failure here");

或者,

Assert.assertEquals(1, 2);

甚至:

throw new AssertionException(e);

这取决于你使用的Junit版本。 Junit 4- 将区分故障和错误,但 Junit 4 将其简化为仅故障。

以下链接提供了更多有趣的输入:

http://www.devx.com/ Java/Article/31983/1763/page/2

If your test throws an exception which does not get bubbled up through the Assertion framework in Junit, it gets reported as an error. For example, a NullPointer, or a ClassNotFound exception will report an error:

String s = null;
s.trim();

or,

try {

    // your code
} catch(Exception e) {
    // log the exception
    throw new MyException(e);
}

Having said that, the following will report a failure:

Assert.fail("Failure here");

or,

Assert.assertEquals(1, 2);

or even:

throw new AssertionException(e);

It depends on the Junit version you are using. Junit 4- will make the distinction between a failure and an error, but Junit 4 simplifies it as failures only.

Following link provides more interesting inputs:

http://www.devx.com/Java/Article/31983/1763/page/2

じ违心 2024-09-20 09:16:07

来自“使用 JUnit 在 Java 8 中进行实用单元测试”:

JUnit 中的断言(或断言)是您放入的静态方法调用
你的测试。每个断言都是一个机会来验证某些条件
确实如此。如果断言条件不成立,则测试立即停止
那里,JUnit 报告测试失败。

(也有可能当 JUnit 运行测试时,抛出异常并
没有被抓住。在这种情况下,JUnit 会报告测试错误。)

From "Pragmatic Unit Testing in Java 8 with JUnit":

Assertions (or asserts) in JUnit are static method calls that you drop into
your tests. Each assertion is an opportunity to verify that some condition
holds true. If an asserted condition does not hold true, the test stops right
there, and JUnit reports a test failure.

(It’s also possible that when JUnit runs your test, an exception is thrown and
not caught. In this case, JUnit reports a test error.)

彼岸花ソ最美的依靠 2024-09-20 09:16:07

下面的测试解释了测试错误与测试失败之间的区别。

我已经评论了引发测试错误和测试失败的行。

    @Test
    public void testErrorVsTestFailure() {

        final String sampleString = null;

        assertEquals('j', sampleString.charAt(0) );
        //above line throws test error as you are trying to access charAt() method on null reference

        assertEquals(sampleString, "jacob");
        //above line throws Test failure as the actual value-a null , is not equal to expected value-string "jacob"
        }

因此,每当出现异常时,Junit 就会显示测试错误,而当预期结果值与实际值不匹配时,Junit 就会显示测试失败

Below test explains the difference between Test Error vs Test failure.

I have commented the line which throws test error and test failure.

    @Test
    public void testErrorVsTestFailure() {

        final String sampleString = null;

        assertEquals('j', sampleString.charAt(0) );
        //above line throws test error as you are trying to access charAt() method on null reference

        assertEquals(sampleString, "jacob");
        //above line throws Test failure as the actual value-a null , is not equal to expected value-string "jacob"
        }

So Junit shows test error whenever you get an exception , and test failure when your expected result value doesn't match your actual value

千年*琉璃梦 2024-09-20 09:16:07

源类:JUnitReportReporter.java

public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String defaultOutputDirectory) {
//......

            for (ITestResult tr : (Set) entry.getValue()) {
                TestTag testTag = new TestTag();

                boolean isSuccess = tr.getStatus() == 1;
                if (!(isSuccess)) {
                    if (tr.getThrowable() instanceof AssertionError)
                        ++errors;
                    else {
                        ++failures;
                    }
                }
}

正如您在上面方法中看到的下面一行

tr.getThrowable()实例断言错误

错误计数当它是 AssertionError 实例时会增加,否则(任何 Throwable)将被计为失败。

Source class : JUnitReportReporter.java

public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String defaultOutputDirectory) {
//......

            for (ITestResult tr : (Set) entry.getValue()) {
                TestTag testTag = new TestTag();

                boolean isSuccess = tr.getStatus() == 1;
                if (!(isSuccess)) {
                    if (tr.getThrowable() instanceof AssertionError)
                        ++errors;
                    else {
                        ++failures;
                    }
                }
}

As you can see below line in above method

tr.getThrowable() instanceof AssertionError

errors count is increased when it is instance of AssertionError otherwise(any Throwable) is counted as failures.

但可醉心 2024-09-20 09:16:07

你是对的,失败来自于 JUnit 断言方法抛出的 AssertionError,或者抛出 AssertionError,或者抛出你在 @Test 注释中声明的异常,而错误来自其他意外的情况。例外情况。但它们之间有一个重要的区别:

失败意味着您的测试运行正确,并发现了代码中的缺陷。

错误可能意味着代码中存在错误,但您甚至没有对其进行测试。这也可能意味着该错误存在于测试本身中。

简而言之,失败意味着您需要重写正在测试的代码。错误意味着它可能是您需要重写的单元测试。即使故障发生在您的代码中(例如 NullPointerException ),这也可能意味着这一点,因为您检测到了一个甚至没有测试的缺陷,因此测试该缺陷可能是明智的。

You are right that failures come from the AssertionErrors thrown by the JUnit assertion methods, or by throwing an AssertionError, or by throwing an exception that you declared in your @Test annotation, and Errors come from other, unexpected Exceptions. But there's an important distinction between them:

A failure means your test ran correctly, and identified a defect in your code.

An error could mean a bug in your code, but one that you weren't even testing for. It could also mean that the bug is in the test itself.

In short, a failure means you need to rewrite the code that is being tested. An error means that it may be the unit test that you need to rewrite. It may mean this even if the failure was in your code, such as a NullPointerException, because you detected a flaw that you weren't even testing for, so it might be wise to test for that.

醉态萌生 2024-09-20 09:16:07
测试方法抛出测试结果
java.lang.AssertionError失败
org.junit.AsductionViolatedException跳过了
预期的异常OK
任何其他异常错误
无异常OK
测试方法之外的异常 错误
  • 断言方法只是抛出 AssertionExceptions。
  • @Test 注释中预期会声明异常。
  • 测试方法之外的代码可以用@Before注释,
    @BeforeClass 等等。
  • IDE 报告中的计数对测试(测试方法)进行计数,而不是对断言进行计数,因为第一个失败的断言会终止测试。
  • 根据经验,如果测试方法异常终止(未使用 return 语句),则测试方法不成功,反之亦然。
Test Method ThrowsTest Outcome
java.lang.AssertionErrorfailure
org.junit.AssumptionViolatedExceptionskipped
an expected exceptionOK
any other exceptionerror
no exceptionOK
exception outside of a test methoderror
  • The assert methods just throw AssertionExceptions.
  • An exception is declared expected in the @Test annotation.
  • Code outside of test methods can be stuff annotated with @Before,
    @BeforeClass and so on.
  • The counts in the IDE reports count tests (test methods), not assertions, because the first failed assertion terminates the test.
  • As a rule of thumb, if the test method terminates abnormally (not with a return statement), it is unsuccessful, and vice versa.
年华零落成诗 2024-09-20 09:16:07

讽刺的是,junit 和其他测试相关框架(testng、hamcrest)提供了验证条件的断言操作,如果它失败,那么“在幕后”将抛出 java.lang.AssertionError ,顺便说一句扩展 java.lang.Error。

但这与上面的答案并不矛盾,当然,这些答案是完全有效的。因此,为了将特定的测试流程标记为失败,可以抛出 AssertionError,但是我不确定它是否真的记录在相应的手册中,因为使用专用的fail() API更合适。其他类型的 Throwable 将被视为错误,而不是失败。

Ironically, junit and other testing related frameworks (testng, hamcrest) provide assert operations which verify condition and if it fails then "under-the-hood" a java.lang.AssertionError is being thrown, which btw extends java.lang.Error.

But it no way contradicts with answers above which are fully valid of course. So in order to mark specific test flow as failure one can throw AssertionError, however I'm not sure it's really documented in corresponding manuals, because more appropriate to use dedicated fail() API. Other kinds of Throwable will be considered as errors, not failures.

星星的轨迹 2024-09-20 09:16:07

基本上,失败是指未实现的断言,而错误是由于测试执行异常。我认为每个 IDE 都有不同颜色的符号图标,用于通过失败有错误测试。

如需了解更多信息,请查看

Basically, failures refer to unfulfilled assertions while errors are due to abnormal test execution. and I think each IDE has symbolic icons with different colors for passed, failed, and with error tests.

For more information, check this.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文