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
Vj@88Vj@88 

Formula fields evaluation in Test classes

Hi,

I wrote some apex code that will based on the result of a formula field. It works fine with real data.
But the problem is when I try to generate mock data in test class, the formula field is not evaluating and is always 'Null'.
Can annybody help me how to get the formula field evaluated?

 
Best Answer chosen by Vj@88
YuchenYuchen
In Test Class, if you want to get the value after insertion, you may have to query again. So you can have something like this:

Account theAcc = [SELECT ID, Region__c FROM Account WHERE ID-: A[0].id limit 1];

Then you should be able to access "theAcc.Region__c".

All Answers

YuchenYuchen
Generally the formula field should have value in Test Class, could you share your formula and Test Class code so that we can take a look?
Vj@88Vj@88
The code is too long to paste it here. But it is easy to replicate the scenario. PFB below code
@IStest

public class testformulafield
{
    @Istest
    public static void testFF()
    {
        list<account> A = TestUtils.createaccounts(1);
        insert A;
        
        System.Debug(A[0].region__c);
        
        }
        
        }

Region__c is a formula field on Acount that copies the region of the Account Owner User.
14:02:02.956 (3956927005)|SYSTEM_METHOD_ENTRY|[11]|System.debug(ANY)
14:02:02.956 (3956977555)|USER_DEBUG|[11]|DEBUG|null
14:02:02.956 (3956991249)|SYSTEM_METHOD_EXIT|[11]|System.debug(ANY)

Now this is what I got in debug logs. A null value
 
YuchenYuchen
In Test Class, if you want to get the value after insertion, you may have to query again. So you can have something like this:

Account theAcc = [SELECT ID, Region__c FROM Account WHERE ID-: A[0].id limit 1];

Then you should be able to access "theAcc.Region__c".
This was selected as the best answer
Vj@88Vj@88
Yes I tried that before. But do you know the reason why we the formula field is blank for A[0]