Reputation: 65
First, I am new to Java, so hopefully this isn't something terribly simple, but I am trying to do some unit-testing and I am not getting the old green light in Eclipse. To my problem:
So, I have two Objects, both of class Fraction and I am simply trying to make sure that my method (multiplyThem) is.... uh... functioning correctly.
Code (edited to show what I have now):
private Fraction newFraction, otherFraction, thirdFraction;
@Before
public void setUp(){
newFraction = new Fraction(2, 3);
otherFraction = new Fraction(1, 5);
thirdFraction = new Fraction(2, 15);
}
@Test
public void testMultiplyEm() {
System.out.println(newFraction.multiplyEm(otherFraction));
System.out.println(thirdFraction);
assertEquals("Fractions don't equal", newFraction.multiplyEm(otherFraction), thirdFraction);
}
In the method multiplyEm
, the return type is a Fraction and it multiplies two numerators and two denominators before calling on another function called simplify. Then it returns the simplified Fraction.
I used System.out.println
on the two individually and got the exact same thing printed to screen. I know that doesn't always mean they ARE the same, but perhaps Objects.equals
isn't what I should be using here. The objects are simply two ints: Fraction x = new Fraction(int y, int z)
.
I am not sure why this fails the test. Anyone have any ideas? Would be grateful for a way to correctly write a unit test for it!
Fraction Class method multiplyEm:
public Fraction multiplyEm(Fraction otherFraction){
int newNumerator = this.numerator * otherFraction.numerator;
int newDenominator = this.denominator * otherFraction.denominator;
Fraction newFraction = new Fraction(newNumerator, newDenominator);
return newFraction;
}
Upvotes: 1
Views: 2210
Reputation: 3295
You are running into the difference between object identity and equality. The equals method checks either the identity or the equality based on the implementation. The ==
operator always checks the identity of an object.
The Objects.equals method checks for null references and then delegates the check to the equals method of the first argument.
The equals method inherited from the Object class checks the identity of the objects. That the object reference is the same. The Fraction
class should override the equals implementation. There are some rules for correctly implementing the equals method. There is a contract for the equals and hashCode methods that needs to be honoured for the Java Collections to work correctly.
Included in the JUnit framework is an assertEquals method. That is the method usually used to test equality in a unit test.
Upvotes: 3