[Bluej-discuss] Unit Testing with Java 6 and BlueJ 2.2.0
Michael Kölling
M.Kolling at kent.ac.uk
Wed Sep 12 09:31:15 BST 2007
The problem here is with method overloading and auto-boxing/unboxing.
For a start, we have two method definitions:
assertEquals(Object, Object)
and
assertEquals(int, int)
When I make a call to assertEquals, the compiler tries to figure out
which one to call by looking at the parameters. Thus, when I call
assertEquals(3, 4);
the assertEquals(int, int) method will be invoked; when I call
assertEquals(new Integer(3), new Integer(4));
the assertEquals(Object, Object) method will be invoked.
Now, this does not necessarily have to be the case. Assume we did not
have the (int, int) method at all. Then the call
assertEquals(3, 4);
would quite happily invoke the assertEquals(Object, Object) method,
since the parameters would just be auto-boxed, and off we go. (The
same goes the other way around with unboxing.) In other words: my
method call above actually conforms to _both_ method signatures.
In this case, Java has a concept of a "best match". It will choose
the method that requires least conversion of the parameters. So for
ints, the int method is called, for Integers the Object method.
Now let's look at your case. In your call
assertEquals(1, Fraction.gcf(17, 31));
the types of your arguments are (int, Integer). In this case, when
Java tries to decide the best match, it cannot decide: we could
convert the first argument and call one method, or convert the second
and call the other. The score is even. So you get the "ambiguous
match" message.
You can solve this by casting explicitly. For instance
assertEquals(1, (int) Fraction.gcf(17, 31));
will now invoke the (int, int) method.
Michael
On 11 Sep 2007, at 22:57, Lon Levy wrote:
> Greetings,
>
> When I was working with my first unit tests of the school year, I
> got the following error message:
>
> reference to assertEquals is ambiguous, both method assertEquals
> (java.lang.Object, java.lang.Object) in junit.framework.Assert and
> method assertEquals(int, int) in junit.framework.Assert match
>
> The particular line in my test is:
>
> assertEquals(1, Fraction.gcf(17, 31));
>
> and the static gcf method of the Fraction class that I wrote should
> return an Integer.
>
> I don't recall this problem last year when I was using Java 5 and
> BlueJ 2.1.3
>
> Recommendations? Help!
>
> Thank you,
>
> Lon.
>
> Lon Levy, MS-CSEd
> Computer Science Teacher
> Volunteer Computer Club Advisor
> Oregon High School
> 608-835-1316
>
> Lon.Levy at oregonsd.org
> LXL at oregon.k12.wi.us
> cs at levytree.net
>
> non somnos requiem
>
>
> _______________________________________________
> mailing list bluej-discuss at bluej.org
> To unsubscribe or change your preferences, go to
> http://lists.bluej.org/mailman/listinfo/bluej-discuss
More information about the bluej-discuss
mailing list