有人知道为什么JUnit 4提供assertEquals(foo,bar)方法而不提供assertNotEqual(foo,bar)方法吗?
它提供了assertNotSame(对应于assertSame)和assertFalse(对应于assertTrue),所以它们没有包含assertnotqual似乎很奇怪。
顺便说一下,我知道JUnit-addons提供了我正在寻找的方法。我只是出于好奇才问的。
有人知道为什么JUnit 4提供assertEquals(foo,bar)方法而不提供assertNotEqual(foo,bar)方法吗?
它提供了assertNotSame(对应于assertSame)和assertFalse(对应于assertTrue),所以它们没有包含assertnotqual似乎很奇怪。
顺便说一下,我知道JUnit-addons提供了我正在寻找的方法。我只是出于好奇才问的。
当前回答
对于否定的断言,最好使用Hamcrest,而不是assertFalse,因为在前者中,测试报告将显示断言失败的差异。
如果使用assertFalse,只会在报告中得到一个断言失败。例如,丢失了关于失败原因的信息。
其他回答
我也想知道。Assert的API不是很对称;对于测试对象是否相同,它提供了assertSame和assertNotSame。
当然,写起来也不算太长:
assertFalse(foo.equals(bar));
不幸的是,使用这样的断言,输出中唯一有信息的部分是测试方法的名称,因此应该单独形成描述性消息:
String msg = "Expected <" + foo + "> to be unequal to <" + bar +">";
assertFalse(msg, foo.equals(bar));
这当然是非常乏味的,最好是滚动您自己的assertNotEqual。幸运的是,将来它可能会成为JUnit: JUnit第22期的一部分
我在java 8环境下的JUnit工作,使用jUnit4.12
对我来说:编译器无法找到方法assertNotEquals,即使当我使用 进口org.junit.Assert;
所以我改变assertNotEquals("addb",字符串);assertNotEquals(“addb”字符串);
因此,如果您面临关于assertNotEqual不被识别的问题,则将其更改为Assert.assertNotEquals(,);它应该能解决你的问题
我来这个派对很晚了,但我发现了表格:
static void assertTrue(java.lang.String message, boolean condition)
可以用于大多数“不等于”的情况。
int status = doSomething() ; // expected to return 123
assertTrue("doSomething() returned unexpected status", status != 123 ) ;
JUnit 4.11中有一个assertNotEquals: https://github.com/junit-team/junit/blob/master/doc/ReleaseNotes4.11.md#improvements-to-assert-and-assume
import static org.junit.Assert.assertNotEquals;
I'd argue that the absence of assertNotEqual is indeed an asymmetry and makes JUnit a bit less learnable. Mind that this is a neat case when adding a method would diminish the complexity of the API, at least for me: Symmetry helps ruling the bigger space. My guess is that the reason for the omission may be that there are too few people calling for the method. Yet, I remember a time when even assertFalse did not exist; hence, I have a positive expectation that the method might eventually be added, given that it is not a difficult one; even though I acknowledge that there are numerous workarounds, even elegant ones.