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?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In JUnit4 the exception (actually Error) thrown by a JUnit assert is the same as the error thrown by the java
assertkeyword (AssertionError), so it is exactly the same asassertTrueand 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
assertTrueis the better practice, because it guarantees the test is run, ensures consistency (you sometimes useassertThator 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.