jUnit failed() 约定
我想知道,按照惯例,当测试失败时,是否适合:
- 说出为什么失败(业务逻辑)
- 说出为什么看到消息(应该抛出异常,但没有)
例如,
fail("Accessed the element which does not exist");
或者
fail("ArrayIndexOutOfBoundException was expected but something bad happened");
通常首选哪一个/接受?
I am wondering, by convention, when a test fails, is it appropriate to:
- Say why it failed (business logic)
- Say why the message is seen (exception should have been thrown and it's not)
For instance,
fail("Accessed the element which does not exist");
or
fail("ArrayIndexOutOfBoundException was expected but something bad happened");
Which one is generally preferred/ accepted?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,如果您希望测试的 API 抛出异常,而不是使用
fail()
执行try-catch
......您应该这样做:-
也就是说,我很少使用
fail()
。如果我需要执行某些验证并且条件失败,我很可能会使用断言而不是使用fail()
... 例如:-... 而不是...
... 这样做:-
但是,如果您确实需要使用
fail()
,请详细说明它失败的原因,而不是“不应该到达此处”或“应该在此处失败”,因为这对以下人员没有帮助:阅读测试用例。当然,这些只是简单的例子……但我想我已经明白了我的观点。 :)
First, if you expect the API you test to throw an exception, instead of doing a
try-catch
with afail()
...... you should do this:-
That said, I rarely use
fail()
. If I need to perform certain validation and the condition fails, I will most likely use assertions than usingfail()
... for example:-... instead of...
... do this:-
However, if you really need to use
fail()
, be verbose and explain why it fails rather than "should not reach here" or "should fail here" because that doesn't help folks who read the testcases.Granted, these are just simple examples.... but I think I get my points across. :)
鉴于这是测试代码,不应该将其纳入最终版本,我想说越详细越好。因此,我会选择第一个 - 它更清楚问题的根本原因是什么,这使得更容易纠正。
在任何情况下我都会避免使用第二个,因为它对测试人员来说不是很有帮助,并且如果它确实以某种方式进入最终版本,那么对于最终用户来说,它比第一个更加神秘 - 它对测试人员或其他人来说根本没有帮助用户一样。
我考虑的另一种选择是不指示发生了异常,而是提供实际异常的详细信息 - 这就是发明堆栈跟踪的原因。这将比列出的任何一种方法传达更多的细节。
Given that this is testing code and shouldn't make it into the final build, I'd say the more verbose the better. As such, I'd go with the first one - it's much clearer what the root cause of the problem is, which makes it easier to correct.
I'd avoid the second one under all circumstances because it's not very helpful for a tester, and if it does somehow make it into the final build its even more cryptic than the first to an end user - it simply is no help for testers or users alike.
The one other option that I'd consider is rather than indicating that an exception occurred, instead give details of the actual exception - that's why stack traces were invented. That would convey more detail than either method listed.
如果有关于此的约定,我会忽略它。您应该说最能向看到此消息的人传达问题本质的任何内容,以便尽可能轻松地解决问题。在这方面,遵守惯例常常会失败。
If there were a convention about this I would ignore it. You should say whatever will best communicate to someone seeing this message the nature of the problem in such a way that it can be resolved as easily as possible. Too often adhering to a convention fails in this regard.