问题描述
JUnit4 库中有一个 fail()
方法.我喜欢它,但遇到了库中不存在的 pass()
方法的缺乏.为什么会这样?
There is a fail()
method in JUnit4 library. I like it, but experiencing a lack of pass()
method which is not present in the library. Why is it so?
我发现我可以使用 assertTrue(true)
代替,但看起来仍然不合逻辑.
I've found out that I can use assertTrue(true)
instead but still looks unlogical.
@Test
public void testSetterForeignWord(){
try {
card.setForeignWord("");
fail();
} catch (IncorrectArgumentForSetter ex){
}
// assertTrue(true);
}
推荐答案
只要测试没有抛出异常,它就会通过,除非您的 @Test
注释指定了预期的异常.我想 pass()
可能会抛出一个特殊的异常,JUnit 总是将其解释为通过,从而使测试短路,但这会违背通常的测试设计(即假设成功,只有失败如果断言失败),并且如果人们认为使用 pass()
更好,这将显着减慢大量通过测试的速度(由于异常创建的开销).失败的测试不应该是常态,所以如果他们有这样的开销也没什么大不了的.
As long as the test doesn't throw an exception, it passes, unless your @Test
annotation specifies an expected exception. I suppose a pass()
could throw a special exception that JUnit always interprets as passing, so as to short circuit the test, but that would go against the usual design of tests (i.e. assume success and only fail if an assertion fails) and, if people got the idea that it was preferable to use pass()
, it would significantly slow down a large suite of passing tests (due to the overhead of exception creation). Failing tests should not be the norm, so it's not a big deal if they have that overhead.
请注意,您的示例可以像这样重写:
Note that your example could be rewritten like this:
@Test(expected=IncorrectArgumentForSetter.class)
public void testSetterForeignWord("") throws Exception {
card.setForeignWord("");
}
此外,您应该倾向于使用标准的 Java 异常.你的 IncorrectArgumentForSetter
应该是一个 IllegalArgumentException
.
Also, you should favor the use of standard Java exceptions. Your IncorrectArgumentForSetter
should probably be an IllegalArgumentException
.
这篇关于JUnit4 fail() 在这里,但是 pass() 在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!