Oğuz Gecir
Oğuz Gecir

Reputation: 57

IntelliJ test fails

Hi I'm trying to test my Calculator.java class with a test case but I get this error :

java.lang.AssertionError: expected:<3> but was:main.Calculator@5bb21b69 Expected :3 Actual :main.Calculator@5bb21b69

This is the test case I wrote

public class CalculatorTest {
    @Test
    public void testCalculator(){
        Calculator calculator = new Calculator();
        calculator.calculate(5,2,'-');
        Assert.assertEquals(3,calculator);

    }

And this is my calculator class

package main;

public class Calculator {



    public Double calculate(double first, double second, char operator) {
        double result;

        switch (operator) {
        case '+':
            result = first + second;
            break;

        case '-':
            result = first - second;
            break;

        case '*':
            result = first * second;
            break;

        case '/':
            result = first / second;
            break;

        // operator doesn't match any case constant (+, -, *, /)
        default:
            System.out.printf("Error! operator is not correct");
            return null;
        }
        return result;
    }

}

Upvotes: 0

Views: 113

Answers (3)

chptr-one
chptr-one

Reputation: 610

public class CalculatorTest {
    
    @Test
    public void testCalculator() {
        Calculator calculator = new Calculator();
        double actual = calculator.calculate(5, 2, '-');
        Assert.assertEquals(3.0, actual);
    }
}

And this test will fall because you divide doubles, not integers.

Upvotes: 1

Akif Hadziabdic
Akif Hadziabdic

Reputation: 2890

You have two problems:

  • Wrong actual value

  • Wrong double comparison in case of floating points

     Calculator calculator = new Calculator();
     double value = calculator.calculate(5,2,'-'); // use result from calculation
     Assert.assertTrue(Math.abs(3 - value) <= 0.000001); 
    

Upvotes: 2

SZuber
SZuber

Reputation: 1

You're trying to assert that the result of your test, 3, is equal to a your calculator object. You want the second argument of the assert to be the calculated value, not the calculator object.

Upvotes: 0

Related Questions