Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are JUnit assert methods not generic in Java?

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.

like image 357
Anmol Gupta Avatar asked Aug 05 '16 10:08

Anmol Gupta


People also ask

What is the difference between JUnit 4 and JUnit 5 assertions?

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.

How do you use assertEquals In JUnit?

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.

How to assert that expected value and actual value are equal JUnit?

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.

How to use static import with JUnit class assert?

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.


1 Answers

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.

like image 180
Andy Turner Avatar answered Sep 28 '22 05:09

Andy Turner