为什么我的 Junit-AssertionError-Test 会失败?

Why does my Junit-AssertionError-Test fail?

我 运行 在我的 Eclipse 中进行以下测试(带有参数 -ea):

public class ColorHelperTest
{
    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void testGetColorByString()
    {
        thrown.expect(AssertionError.class);
        assert 1 == 2;
    }
}

输出为:

java.lang.AssertionError
at de.*.*.*.mytests.ColorHelperTest.testGetColorByString(ColorHelperTest.java:28)

28 是行 assert 1==2

为什么这个测试失败了?

assert关键字是JRE级别的标志,与JUnit无关。我认为您真正要找的是:

assertEquals(1, 2);

您不能 "expect" AssertionError,这是 JUnit 用来表示测试失败的特定错误类型。

Update:原来是JUnit 4.11的bug,4.12解决了: https://github.com/junit-team/junit/blob/master/doc/ReleaseNotes4.12.md#pull-request-583-pull-request-720-fix-handling-of-assertionerror-and-assumptionviolatedexception-in-expectedexception-rule

有趣...您使用的是哪个版本的 Junit?使用 4.12(在我的 pom.xml 中看起来像:

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>

完全相同的测试对我有效。