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
tony2009tony2009 

formula in test method

Hi Guys,

 

For some reason, All my the formula value are null in my APEX test method, but works all right if I manually insert some data from user interface. Is it normal?

 

But I really need some formula value for the query condition of APEX SOQL. 

 

Thanks in advance

 

 

 

 

 

 

 

 

Best Answer chosen by Admin (Salesforce Developers) 
TheIntegratorTheIntegrator

After you insert/update an object in test class for which you need to access its formula, you will need to query to get the value of the formula, something like this:

 

 Invoice__c inv = new Invoice__c(
            Date__c = system.today()
        );
        insert(inv);
        system.debug('before query: '+inv.testDate__c);
        Invoice__c i=[Select testDate__c from Invoice__c where Id = :inv.Id];
        system.debug('after query: '+i.testDate__c);

 

Here, testDate__c is a formula field based on the Date__c field, the first debug statement shows null, the second one shows the set value of the formula.

 

All Answers

TheIntegratorTheIntegrator

After you insert/update an object in test class for which you need to access its formula, you will need to query to get the value of the formula, something like this:

 

 Invoice__c inv = new Invoice__c(
            Date__c = system.today()
        );
        insert(inv);
        system.debug('before query: '+inv.testDate__c);
        Invoice__c i=[Select testDate__c from Invoice__c where Id = :inv.Id];
        system.debug('after query: '+i.testDate__c);

 

Here, testDate__c is a formula field based on the Date__c field, the first debug statement shows null, the second one shows the set value of the formula.

 

This was selected as the best answer
tony2009tony2009

thanks, it works perfect.  :)

FlorentFlorent

Hi

 

I've got the same problem, with the difference that I can't run the insert() prior to updating the formula field, because a validation rule answers false. This validation rule answers false because value of formula field is null…

 

And also, to run the trigger (on insert…), I definitely need to have a value different from null.

 

Bit of a snake biting its own tail…