简体   繁体   English

断言与JUnit断言

[英]assert vs. JUnit Assertions

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

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. 在JUnit4中,JUnit断言抛出的异常(实际上是Error)与java assert关键字(AssertionError)抛出的异常相同,所以它与assertTrue完全相同,而不是堆栈跟踪,你无法区分它们。

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. 话虽如此,断言必须在JVM中使用特殊标志运行,导致许多测试似乎只是因为有人在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. 一般来说,正因为如此,我认为使用JUnit assertTrue是更好的做法,因为它保证测试运行,确保一致性(你有时使用assertThat或其他不是java关键字的断言)以及如果JUnit断言将来应该更改(例如挂钩到某种过滤器或其他未来的JUnit功能),您的代码将能够利用它。

The real purpose of the assert keyword in java is to be able to turn it off without runtime penalty. java中assert关键字的真正目的是能够在没有运行时惩罚的情况下关闭它。 That doesn't apply to unit tests. 这不适用于单元测试。

我更喜欢JUnit断言,因为它们提供比内置assert语句更丰富的API,更重要的是不需要像assert那样显式启用,这需要-ea JVM参数。

When a test fails you get more infomation. 当测试失败时,您会获得更多信息。

assertEquals(1, 2); results in java.lang.AssertionError: expected:<1> but was:<2> 结果在java.lang.AssertionError: expected:<1> but was:<2>

vs VS

assert(1 == 2); results in java.lang.AssertionError 导致java.lang.AssertionError

you can get even more info if you add the message argument to assertEquals 如果将消息参数添加到assertEquals则可以获得更多信息

I'd say use JUnit asserts in test cases, and use java's assert in the code. 我会说在测试用例中使用JUnit断言,并在代码中使用java的断言。 In other words, real code shall never have JUnit dependencies, as obvious, and if it's a test, it should use the JUnit variations of it, never the assert. 换句话说,真正的代码永远不会有JUnit依赖,很明显,如果它是一个测试,它应该使用它的JUnit变体,而不是断言。

I would say if you are using JUnit you should use the JUnit assertions. 我会说如果你使用的是JUnit,你应该使用JUnit断言。 assertTrue() is basically the same as assert , Otherwise why even use JUnit? assertTrue()assert基本相同,否则为什么甚至使用JUnit?

This may not apply if you exclusively use stuff that's shiny and new, but assert was not introduced into Java until 1.4SE. 如果您专门使用闪亮和新的东西,这可能不适用,但断言直到1.4SE才引入Java。 Therefore, if you must work in an environment with older technology, you may lean towards JUnit for compatibility reasons. 因此,如果您必须在具有较旧技术的环境中工作,则出于兼容性原因,您可能倾向于使用JUnit。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM