I am using JUnit 4.12. The assert methods are not generic in nature. For instance, assertEquals method looks like:
static public void assertEquals(Object expected, Object actual) {..}
Why is it not like?
static public <T> void assertEquals(T expected, T actual) {..}
I felt need for generic method declaration for better compile time checking and IDE auto completion.
Deep diving into the actual implementation of Assertions, both JUnit 4 and JUnit 5 have different classes that contemplate various assert methods each serving its own unique purpose. JUnit 4 has all the assert methods under the Assert class while JUnit 5 has all the assert methods under the Assertions class.
JUnit assertEquals. You have assertEquals(a,b) which relies on the equals() method of the Object class. Here it will be evaluated as a.equals( b ). Here the class under test is used to determine a suitable equality relation.
To keep things simple, all JUnit Jupiter assertions are static methods in the org.junit.jupiter.Assertions class. Use Assertions.assertEquals () to assert that expected value and actual value are equal. assertEquals () has many overloaded methods for different data types e.g. int, short, float, char etc.
Using static import with JUnit class Assert, there is no need to include Assert.assertSame () or Assert. With any of its static assertion methods for that matter. This gives easy and shorter access to the method calls. package ordertests.com; import static org. junit. Assert. *; import org. junit.
Having a generic method like this:
<T> void assertEquals(T expected, T actual) { /* ... */ }
gives you no type safety to avoid comparing unlike types: you can pass in anything to this method, since T
degenerates to its upper bound, Object
:
assertEquals("string", 0); // Compiles fine, even though they can't be equal.
Ideone demo
And nor can you use any methods on expected
and actual
that aren't found on Object
. So, T
is basically just Object
.
As such, adding generics is just over-complicating the implementation.
Now, you could define a class like this:
class GenericAssert<T> {
void assertEquals(T expected, T actual) { /* ... */ }
}
and you could use this like:
new GenericAssert<String>().assertEquals("string", 0); // Compiler error.
because you've now placed a tighter upper bound on the acceptable parameters of assertEquals
, at class level.
But this just feels a bit awkward.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With