0

Given the test code below the property originalOrderAmount is null but it has to be 100. What am I doing wrong?

Controller:

@TestVisible
    public Decimal originalOrderAmount {
        private set {
        }
        get {
            if (originalOrderAmount == null && !Test.isRunningTest()) {
                originalOrderAmount = Decimal.valueOf(ApexPages.currentPage().getParameters().get('OrderAmount'));
            }

            return originalOrderAmount;
        }
}

Test class:

 static testMethod void testCreditNoteProject(){
   CreditNoteController cnc = new CreditNoteController();
   cnc.originalOrderAmount = 100;
   System.debug(cnc.originalOrderAmount); // originalOrderAmount = null
 }
0

Your setter is not correct and you didn't code for assignment. Thats why value is not getting assigned. Following is the corrected code:

@TestVisible
    public Decimal originalOrderAmount {
        private set {
            originalOrderAmount = value;
        }
        get {
            if (originalOrderAmount == null && !Test.isRunningTest()) {
                originalOrderAmount = Decimal.valueOf(ApexPages.currentPage().getParameters().get('OrderAmount'));
            }

            return originalOrderAmount;
        }
}

Test class

static testMethod void testCreditNoteProject(){
    CreditNoteController cnc = new CreditNoteController();
    cnc.originalOrderAmount = 100;
    System.assertEquals(Decimal.valueOf('100'), cnc.originalOrderAmount);
}
1

When defining Setters and getters if you use the code block form you have to provide the body of the setter:

@TestVisible
public Decimal originalOrderAmount {
    private set {
        originalOrderAmount = value;
    }
    get {
        if (originalOrderAmount == null && !Test.isRunningTest()) {
            originalOrderAmount = Decimal.valueOf(ApexPages.currentPage().getParameters().get('OrderAmount'));
        }

        return originalOrderAmount;
    }
}

If you just want it to set the value with no additional logic, simply remove the block {} and use the shorthand and the default setter will be used

@TestVisible
public Decimal originalOrderAmount {
    private set;
    get {
        if (originalOrderAmount == null && !Test.isRunningTest()) {
            originalOrderAmount = Decimal.valueOf(ApexPages.currentPage().getParameters().get('OrderAmount'));
        }

        return originalOrderAmount;
    }
}

Both are valid, the first is just superfluous.

and you test would be almost the same

static testMethod void testCreditNoteProject(){
    CreditNoteController cnc = new CreditNoteController();
    cnc.originalOrderAmount = 100;
    System.assertEquals(100, cnc.originalOrderAmount); //You could also use 100.00 but 100 is equal to 100.00 so it really does not matter.
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.