JUnit4 fail()就在这里,但是pass()在哪里? [英] JUnit4 fail() is here, but where is pass()?

查看:91
本文介绍了JUnit4 fail()就在这里,但是pass()在哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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()在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆