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

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

问题描述

今天我看到了一个 JUnit 测试用例,其中包含一个 java 断言而不是 JUnit 断言——偏爱一个断言是否有明显的优点或缺点?

解决方案

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

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

总的来说,因此,我认为使用 JUnit assertTrue 是更好的做法,因为它保证测试运行,确保一致性(有时您使用 assertThatcode> 或其他不是 java 关键字的断言),并且如果 JUnit 断言的行为在未来发生变化(例如挂钩某种过滤器或其他未来的 JUnit 功能),您的代码将能够利用它.

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

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?

解决方案

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.

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.

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.

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天全站免登陆