0

I'm trying to write the Junit test code for the following code:

public class RateofPay {

   public double totalSalary(double work, double work2, double hour1, double hour2, double hour3) {

    double salary1 = work * hour1;
    double salary2 = work2 * hour2;
    double salary3 = work * hour3;
    double wages = salary1 + salary2 + salary3;
    return wages;
    }
  }

And this is the JUnit test I have wrote:

public class WageTest {

@Test
public void testWage() {
    RateofPay test=new RateofPay();
    double result=test.totalSalary(1.0, 2.0, 3.0, 4.0, 5.0);
    assertEquals(12.0, result);

}

@Test
public void testWage1() {
    RateofPay test=new RateofPay();
    double result=test.totalSalary(6.0, 7.0, 8.0, 9.0, 10.0);
    assertEquals(157.0, result);

 }
}

The problem is that every time when I run the JUnit test, none of them pass the test. The result says

assertEquals(expected, actual, delta) to compare floating point number.

I'm wondering what is wrong? Thanks.

Naman
  • 27,789
  • 26
  • 218
  • 353
Yang
  • 11
  • 1
  • 1
    Please share the failure logs. – Naman Feb 09 '17 at 02:48
  • Looks like math is wrong! it should be 16 and 171! – Santo Feb 09 '17 at 02:48
  • more details regarding the delta are available on http://stackoverflow.com/questions/5939788/junit-assertequalsdouble-expected-double-actual-double-epsilon – Ashish Juyal Feb 09 '17 at 07:14
  • Hint: the **real** solution here is: do some research on your error message. You already had **all** the information you need at hand. When JUnit tells you "please do X"; then heck: go and google what "X" is about. In essence, your problem is that you do not understand how computers deal with floating point numbers; and thus you do not understand how to write code dealing with floating point numbers. So: simply step back, turn to the books and **learn** about "computers & floating point numbers". You can start reading the "duplicated" question I put up; esp. response 3 by madma is for you ... – GhostCat Feb 09 '17 at 07:52

1 Answers1

4

You should specify the delta parameter when trying to compare double numbers. Besides, your assertions are wrong.

They should be like this.

    @Test
    public void testWage() {
        Solution test=new Solution();
        double result=test.totalSalary(1.0, 2.0, 3.0, 4.0, 5.0);
        assertEquals(16.0, result, 0.0);
    }

    @Test
    public void testWage1() {
        Solution test=new Solution();
        double result=test.totalSalary(6.0, 7.0, 8.0, 9.0, 10.0);
        assertEquals(171.0, result, 0.0);

    }

For example, the first test would have this calculation:

double salary1 = 1 * 3; //3
double salary2 = 2 * 4; //8
double salary3 = 1 * 5; //5
double wages = salary1 + salary2 + salary3; // 3 + 8 + 5 = 16
alayor
  • 4,537
  • 6
  • 27
  • 47
  • You could have mentioned at least in a half-sentence *why* one needs to use some *epsilon* when comparing floating point numbers in general. – GhostCat Feb 09 '17 at 07:54