function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
The WalrusThe Walrus 

Test Method returns null value but manual testing works ok

Hello,

 

I have a simple trigger that I am building which somewhat mimics the example in the apex code manual introductory chapters.   For simplicity in building it, I am starting by doing exactly what the example does - reducing a value by 10%.  However, instead of putting the result back into the field used as input to the calculation, I am putting the result in a different field.  Here is the class code:

 

public class InvoicePayment {
      public static void calculatePayment(InvoiceBalance__c[] invoicepayments) {
           for (InvoiceBalance__c i :invoicepayments) {
                                 i.Paid_Since_Last_Report__c = i.Invoice_Balance_Amount__c * 0.9;
                                }
                  }
}

 

Here is the trigger:

 

trigger InvoicePaymentTrigger on InvoiceBalance__c (before insert) {
                            InvoiceBalance__c[] invoicepayments = Trigger.new;
                            InvoicePayment.calculatePayment(invoicepayments);
}



 

And here is the test method:

 

@isTest
Private Class InvoicePaymentTestClass {

static testMethod void validateInvoicePayment() {

InvoiceBalance__c i = new
InvoiceBalance__c(Name='I110811EP3-3', 
Invoice__c = 'a01U000000180Wy',
Invoice_Balance_Amount__c=300);
System.debug('Paid Since Last Report before inserting new balance record:' + i.Paid_Since_Last_Report__c);
//Insert Balance Record
insert i;
//display the payment after the insert
System.debug('Invoice_Balance_Amount__c after inserting new balance record:' + i.Invoice_Balance_Amount__c); 
System.debug('Paid Since Last Report after inserting new balance record:' + i.Paid_Since_Last_Report__c);
//Test that the trigger correctly fired
System.assertEquals(270, i.Paid_Since_Last_Report__c);
}
}

When I run the trigger manually, it works.  But when I run the trigger, the value in Paid_Since_Last_Report__c is null.

 

What am I doing wrong in my test method?  Thanks

 

Best Answer chosen by Admin (Salesforce Developers) 
The WalrusThe Walrus

Oops - I found the problem myself.   I left out the select statement -

 

i = [SELECT Paid_Since_Last_Report__c FROM InvoiceBalance__c WHERE Id = i.Id];

 

immediately after the insert.