断言与JUnit断言 [英] assert vs. JUnit Assertions

查看:148
本文介绍了断言与JUnit断言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我看到了一个带有java断言的JUnit测试用例,而不是JUnit断言 - 是否有优势或缺点让一个优先于另一个?

Today I saw a JUnit test case with a java assertion instead of the JUnit assertions—Are there significant advantages or disadvantages to prefer one over the other?

推荐答案

在JUnit4中,JUnit断言抛出的异常(实际上是Error)与java assert 关键字(AssertionError)抛出的错误相同,因此它与 assertTrue 完全相同,除了堆栈跟踪之外,你无法区分它们。

In JUnit4 the exception (actually Error) thrown by a JUnit assert is the same as the error thrown by the java assert keyword (AssertionError), so it is exactly the same as assertTrue and other than the stack trace you couldn't tell the difference.

话虽如此,断言必须在JVM中使用特殊标志运行,导致许多测试似乎只是因为有人在JUnit测试运行时忘记使用该标志配置系统 - 不好。

That being said, asserts have to run with a special flag in the JVM, causing many tests to appear to pass just because someone forgot to configure the system with that flag when the JUnit tests were run - not good.

一般来说,因为这个,我认为使用JUnit assertTrue 是更好的做法,因为它保证了测试的运行,确保一致性(有时使用 assertThat 或其他不是java k的断言eyword)如果JUnit断言的行为将来会发生变化(例如挂钩到某种过滤器或其他未来的JUnit功能),你的代码就可以利用它。

In general, because of this, I would argue that using the JUnit assertTrue is the better practice, because it guarantees the test is run, ensures consistency (you sometimes use assertThat or other asserts that are not a java keyword) and if the behavior of JUnit asserts should change in the future (such as hooking into some kind of filter or other future JUnit feature) your code will be able to leverage that.

java中assert关键字的真正目的是能够在没有运行时惩罚的情况下将其关闭。这不适用于单元测试。

The real purpose of the assert keyword in java is to be able to turn it off without runtime penalty. That doesn't apply to unit tests.

这篇关于断言与JUnit断言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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