Reputation: 197
I'm trying to make a game of "Rock, papers, scissors". I have tests like these:
@Test
public void rockBeatsScissors() {
assertEquals(rock, rock.vs(scissors));
}
I think it should be enough to write a function Equals, for example:
public class Rock {
Object vs(Scissors s) {
return new Rock();
}
Object vs(Paper p) {
return new Paper();
}
Object vs(Rock r) {
return new Rock();
}
boolean equals(Rock r) {
return true;
}
boolean equals(Paper p) {
return false;
}
boolean equals(Scissors s) {
return false;
}
}
(I know I should add a HashCode function, by the way) I run the tests and I only get failures. What am I doing wrong?
Upvotes: 0
Views: 107
Reputation: 213371
The equals()
method used by assertEquals()
would be the one which takes Object
as argument. Right now, you haven't overridden the Object#equals()
method, but provided your own set of 3 equals method, which wouldn't even be used, and thus the default Object
class method is used, which just does reference comparison.
You've to give following implementation:
/**
* Terrible `equals()` method implementation. Just for demonstration purpose.
*/
@Override
public boolean equals(Object obj) {
return obj instanceof Rock;
}
Upvotes: 3