Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assertEquals doesn't work without second parameter casting

Tags:

java

junit

Folks, why I'm getting the "The method assertEquals(String, Object, Object) is ambiguous for the type DictionaryTest" error for this JUnit test?

@Test
 public void testEditCard() {
  Integer a = 10;
  Integer b = 12;
  Integer c = 2;
  assertEquals("test", a-b, c);
 }

Adding casting assertEquals("test", (Integer)(a-b), c); resolves the problem.

like image 754
Eugene Avatar asked Oct 29 '10 14:10

Eugene


2 Answers

Because of the wonders of autoboxing and -unboxing:

assertEquals("test", /* this is an int */ a-b, /* this is an Integer */ c);

Can be evaluated as

assertEquals(String, long, long);
// in this case the second parameter is unboxed
// (and the first one silently casted)

or as

assertEquals(String, Object, Object);
// in this case the first parameter is boxed

If you declare all variables as int (not Integer), there should be no ambiguity.

like image 199
Sean Patrick Floyd Avatar answered Sep 22 '22 06:09

Sean Patrick Floyd


It's because the compiler can't tell if you want to call assertEquals(String, Object, Object) or assertEquals(String, long, long). Since a-b and c can be automatically coerced to long the compiler sees an ambiguity.

Your explicit cast tells the compiler that you want the Object version.

Note that in this case you could use int rather than Integer variables which would also fix the ambiguity.

like image 35
Cameron Skinner Avatar answered Sep 18 '22 06:09

Cameron Skinner