我在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
行
为什么这个测试失败了?
答案 0 :(得分:2)
你不能“期待”AssertionError
,这是JUnit用来表示测试失败的特定错误类型。
更新:原来这是JUnit 4.11的一个错误,它在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
答案 1 :(得分:1)
assert
关键字是JRE级别标志,与JUnit无关。我认为你真正想要的是:
assertEquals(1, 2);
答案 2 :(得分:1)
有趣......你使用的是什么版本的Junit?使用4.12(在我的pom.xml中看起来像:
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
完全相同的测试适用于我。