Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assert vs. JUnit Assertions

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?

like image 310
Robert Avatar asked Jun 03 '10 13:06

Robert


People also ask

What is JUnit assertion?

Assertions are utility methods to support asserting conditions in tests; these methods are accessible through the Assert class, in JUnit 4, and the Assertions one, in JUnit 5.

How do you use assert in JUnit test cases?

The assertSame() method tests if two object references point to the same object. The assertNotSame() method tests if two object references do not point to the same object. void assertArrayEquals(expectedArray, resultArray); The assertArrayEquals() method will test whether two arrays are equal to each other.

What is the difference between AssertJ and JUnit?

First of all, JUnit is an automated test framework that is built in Java, whereas AssertJ is an opensource library used for writing fluent and rich assertions in Java tests. It's true that you can write assertions just using JUnit, but if you ever have an extra half an hour for studying AssertJ, be sure to go for it.

Is it good practice to use assert?

Yes it is a very good practice to assert your assumptions. Read Design By Contract. assert can be used to verify pre conditions, invariants and post conditions during integration and testing phases. This helps to catch the errors while in development and testing phases.


1 Answers

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.

like image 56
Yishai Avatar answered Sep 20 '22 14:09

Yishai