Search code examples
javaassertassertion

Function returns correct value when printed but fails assertion


I need to write a code for a pension plan.

The main function is such

double pensionTarget = 240000;
double currentSaving = 0;
double annualSalary = 40000;
double monthlySaving = 0.1;
double interestRate = 0.04;

PensionPlanner fp = new PensionPlanner(pensionTarget, currentSaving,
        annualSalary, monthlySaving, interestRate);

System.out.println("Example: Test case 1 working months: " + fp.getWorkingMonth());
assert fp.getWorkingMonth() == 368: "Failed test case 1: Expected working months to be 368, but got " + fp.getWorkingMonth();

The getWorkingMonth() function in the PensionPlanner class is as such

public int getWorkingMonth() {
    double Saving = monthlySaving * (annualSalary / 12);
    int months = 0;

    while (currentSaving < pensionTarget) {
        currentSaving += Saving + (currentSaving * (interestRate / 12));
        months++;
    }

    return months;
}

I keep failing the assertion test.

I have debugged the code and made sure the values are calculated correctly. In the main function this line, does give the expected number of months,

System.out.println("Example: Test case 1 working months: " + fp.getWorkingMonth());

But it fails the assertion and the function getWorkingMonth() returns a value of 0 in this line

assert fp.getWorkingMonth() == 368: "Failed test case 1: Expected working months to be 368, but got " + fp.getWorkingMonth();

I don't know what I'm doing wrong, and would appreciate any help.


Solution

  • You are modifying the instance field currentSaving in the method, so calling getWorkingMonth() a second time will return 0.

    Avoid doing this if you want consistent results. You could use a local variable instead.

    public int getWorkingMonth() {
        double Saving = monthlySaving * (annualSalary / 12);
        int months = 0;
        double curr = currentSaving;
        while (curr < pensionTarget) {
            curr += Saving + (curr * (interestRate / 12));
            months++;
        }
        return months;
    }