views:

345

answers:

5

Today I saw a JUnit test case with a java assertion instead of the JUnit assertions - What are the best practices in this respect?

+7  A: 

I prefer JUnit assertions as they offer a richer API than the built-in assert statement and, more importantly do not need to be explicitly enabled unlike assert, which requires the -ea JVM argument.

Adamski
+1  A: 

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?

CheesePls
You would use JUnit for the test running framework. Asserts are really a small part of the value JUnit gives you. JUnit without `Assert` would require more boilerplate. `assert` without JUnit would require you to write a whole framework.
Yishai
I was more saying if you're going to use the tool, USE THE TOOL. regular old assert statements seem a tad silly in JUnit test cases. They belong in with the actual code in my opinion.
CheesePls
+3  A: 

In JUnit4 the exception (actually Error) thrown by a JUnit assert is is the same the error thrown in 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 test 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.

Yishai
A: 

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.

Dan Coates
A: 

when Java didn't have assert, people bitched and moaned and nagged Sun into adding it.

once Java had it, nobody uses it.

irreputable
Very true. I think it is because they are disabled by default.
Yishai