简体   繁体   中英

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.

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断言,因为它们提供比内置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>

vs

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

you can get even more info if you add the message argument to assertEquals

I'd say use JUnit asserts in test cases, and use java's assert in the code. 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.

I would say if you are using JUnit you should use the JUnit assertions. assertTrue() is basically the same as assert , Otherwise why even use 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. Therefore, if you must work in an environment with older technology, you may lean towards JUnit for compatibility reasons.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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