0

I have written code to + - * / rationals and I am trying to test it with JUnit, I am getting an error, but the expected value and the result value are the same. Is there a way to fix this error.

Code

public ImmutableRational Sub(ImmutableRational rValue)
{
    int resultDenom = LCM(this.denominator,rValue.denominator);
    int resultNum = (this.numerator * (resultDenom / this.denominator)) - (rValue.numerator *(resultDenom/ rValue.denominator));
    ImmutableRational result = new ImmutableRational(resultNum,resultDenom);
    return result;

}

Test

@Test
    public void testSub_ImmutableRational() {
        System.out.println("Sub");
        ImmutableRational rValue = new ImmutableRational(2,3);
        ImmutableRational instance = new ImmutableRational(3,4);
        ImmutableRational expResult = new ImmutableRational(1,12);
        ImmutableRational result = instance.Sub(rValue);
        assertEquals(expResult, result);
        // TODO review the generated test code and remove the default call to fail.
        //fail("The test case is a prototype.");
    }

Error

Testcase: testSub_ImmutableRational(javarational.ImmutableRationalTest):    FAILED
expected: javarational.ImmutableRational<1/12> but was: javarational.ImmutableRational<1/12>
junit.framework.AssertionFailedError: expected: javarational.ImmutableRational<1/12> but was: javarational.ImmutableRational<1/12>
    at javarational.ImmutableRationalTest.testSub_ImmutableRational(ImmutableRationalTest.java:110)

1 Answers1

0

assertEquals checks if two objects are the same by executing the equals method. Have you overwritten the equals method in the ImmutableRational class? If not, then it only checks if it's the same object and thus this is the expected behaviour, since they're not the same object, even though they have the same values.

George
  • 58
  • 7