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
ckellieckellie 

How to query a formula field in my test class

I need to test a validation rule in my test class where the formula field is a date field. From my research, I have developed the code below:

General_Spec_Sheet__c gss2 = new General_Spec_Sheet__c(
       
                            name = 'General Spec Sheet',
                            Opportunity__c = op.id,
                            Customer_Account__c = a.id,
                            Update_Invoice_Billing_Address__c = 'yes',
                            Invoice_to_street__c = '1232 SW Broadway',
                            Invoice_to_City__c = 'Anytown',
                            Invoice_to_State__c = 'AnyState',
                            Invoice_to_Country__c = 'Canada',
                            Invoice_to_Zip_Postal_Code__c = '12345',
                            Technical_Contact__c = con.id,
                            Commercial_Contact__c = con.id,
                            e_mail__c = 'jo@doe.com',
                            phone__c = '5565656456',
                            Update_Technical_Contact_Record__c = 'yes',//Monica
                            Update_Commercial_Contact_Record__c = 'Yes',
                            update__c = 'yes',// Monica
                            Customer_Specific_Standards__c = 'No',
                            fax__c = '1234567898',
                            Generate_Firm_Budget_Quote__c = 'Budget Quote',
                            Requested_Date_to_Complete_Quote__c = date.parse('1/1/2020'));
        try{
             insert gss2;
   

       } Catch(Exception E){
      
       }
    General_Spec_Sheet__c gs = [select id, X3_Day_Minimum_Quote_Due_Date__c from General_Spec_Sheet__c where id=:gss2.id];
     system.debug(' Status Formula Field : ' + gs.X3_Day_Minimum_Quote_Due_Date__c );
     System.assert(gs.X3_Day_Minimum_Quote_Due_Date__c);

I am not able to retrieve the formula value to ttest the validation rule/ How do I retrieve the formula value?

Thank you
ckellie




Below is my entire test class for further reference::

@isTest(SeeAllData=True)
private class TestCreateGeneralSpecSheetListEdit{
   Static CreateGeneralSpecSheetListEdit ext;
   static testMethod void CreateGeneralSpecSheetListEdit () {

    //Setup User
    User u1 = new user (Username = ' test5462@key.net',
                        alias='test',
                        LastName ='test',
                        email='test@key.net',
                        communityNickname='test',
                        TimeZoneSidKey='America/Los_Angeles',
                        LocaleSidKey='en_US',
                        EmailEncodingKey='ISO-8859-1',
                        ProfileId='00e30000000gAkF',
                        LanguageLocaleKey='en_US' );
    insert u1;
         System.runAs(u1) {
         // The following code runs as user 'u1' 
   
         System.debug('Current User: ' + UserInfo.getUserName());
         System.debug('Current Profile: ' + UserInfo.getProfileId()); }

    u1 = [select id from user where alias = 'test'];
   
    //Run as U1

        Test.startTest();
        Account a = new account ( name = 'accounttest', type = 'customer',
        Strategic_Industry__c = 'POT(Potato)', Strategic_Segment__c= 'Chips',
        Strategic_Product__c = 'Kettle chips', billingstreet = '123 south college ave',
        billingcity = 'College Place', billingstate='Washington', billingcountry='United States of America', billingpostalcode ='99324');
        Insert a;
       
        Campaign campaign = new Campaign (name = 'test');
        insert campaign;
       
        Opportunity op = new Opportunity (Recordtypeid = '012300000000Vnm',
                                            Name = 'opportunitytest',
                                            accountid=a.id, //monica
                                            stagename = 'Budget',
                                            CloseDate = date.parse('1/1/2020'),
                                            Amount = 5.00,
                                            INCO_Terms__c = 'FCA',
                                            Campaignid= campaign.id,
                                            Related_Location__c = 'Walla Walla',
                                            Probability_Key_Will_Win_Order__c = 0.01,
                                            ForecastCategoryName = 'Pipeline',
                                            Equip_Services_Options_to_be_quoted__c = 'tegra',
                                            Op_Market_Position__c = '1 - Existing Equip - Existing App/Market (PB items a known app and current cust base)',
                                            Product_1__c = 'apple',
                                            Product1_Condition__c = 'raw',
                                            Product1_Line_Capacity__c = '20000 lbs/hr',
                                            Ready_to_generate_Quote__c = true,
                                            Ready_to_Generate_a_Budget_Quote__c = true,
                                            Requested_date_to_complete_Quote__c = date.parse('1/1/2020'));
        Insert op;
       
        Contact con = new Contact(
                            lastname = 'Doe',
                            Firstname = 'John',
                            email = 'John@does.com',
                            accountid = a.id);
       
        insert con;
    
      
       Customer_Product__c cp = new Customer_Product__c (name ='Apple');
       
        insert cp;
            
        Customer_Product_Line_Item__c cpli = new Customer_Product_Line_Item__c(
                                            name = 'Apple',
                                            customer_Product__c = cp.id,
                                            Opportunity__c = op.id,
                                            Account__c = a.id,
                                            Condition_1__c = 'Raw',
                                            industry_segment__c = 'Pet Food');
       
         insert cpli;

                General_Spec_Sheet__c gss2 = new General_Spec_Sheet__c(
       
                            name = 'General Spec Sheet',
                            Opportunity__c = op.id,
                            Customer_Account__c = a.id,
                            Update_Invoice_Billing_Address__c = 'yes',
                            Invoice_to_street__c = '1232 SW Broadway',
                            Invoice_to_City__c = 'Anytown',
                            Invoice_to_State__c = 'AnyState',
                            Invoice_to_Country__c = 'Canada',
                            Invoice_to_Zip_Postal_Code__c = '12345',
                            Technical_Contact__c = con.id,
                            Commercial_Contact__c = con.id,
                            e_mail__c = 'jo@doe.com',
                            phone__c = '5565656456',
                            Update_Technical_Contact_Record__c = 'yes',//Monica
                            Update_Commercial_Contact_Record__c = 'Yes',
                            update__c = 'yes',// Monica
                            Customer_Specific_Standards__c = 'No',
                            fax__c = '1234567898',
                            Generate_Firm_Budget_Quote__c = 'Budget Quote',
                            Requested_Date_to_Complete_Quote__c = date.parse('1/1/2020'));
        try{
             insert gss2;
   

       } Catch(Exception E){
      
       }
    General_Spec_Sheet__c gs = [select id, X3_Day_Minimum_Quote_Due_Date__c from General_Spec_Sheet__c where id=:gss2.id];
     system.debug(' Status Formula Field : ' + gs.X3_Day_Minimum_Quote_Due_Date__c );
     System.assert(gs.X3_Day_Minimum_Quote_Due_Date__c);

      for(account acct : [select id from account where id =:a.id]){
               if(gss2.Update_Invoice_Billing_Address__c == 'yes'){
               acct.billingstreet = gss2.Invoice_to_street__c;
               acct.billingcity = gss2.Invoice_to_City__c;
               acct.billingstate = gss2.Invoice_to_State__c;
               acct.billingcountry = gss2.Invoice_to_Country__c;
               acct.billingpostalcode = gss2.Invoice_to_Zip_Postal_Code__c;
           update acct;}
          
            system.assertEquals('1232 SW Broadway', acct.billingstreet);
          
           }
        
     Task ta = new Task (
         whatid = op.id,
         subject='Generate a Budget Quote - U.S./Canada',
         ActivityDate = gss2.Requested_Date_to_Complete_Quote__c,
         ownerid= u1.id);
          
           insert ta;
            
      PageReference pageRef2 = Page.GeneralSpecSheetEdit;
   
    pageRef2.getParameters().put('id', gss2.id);

    Test.setCurrentPageReference(pageRef2);
              

        Test.stopTest();
      
                         
        ApexPages.StandardController sc = new ApexPages.StandardController(New General_Spec_Sheet__c());   
      
                           ext = new CreateGeneralSpecSheetListEdit(sc );          
   
   
     String cpUrl = '/apex/GeneralSpecSheetEdit?id=' + gss2.id;

       
        ext.getgess();
        ext.getresults();
        ext.EditGS();
        ext.SendUpdatesandTask();
        ext.CanceltoManage();


           }
   
}
Vinita_SFDCVinita_SFDC
Hi,

Formula fields are calculated on view that is once the record is updated or inserted. To get formula field values in test class you need to insert or update your record before using the formula field value in test class.

Also you can hardcode the formula field value in test class.
ckellieckellie
I have updated the record to create the formula value with the following code:
General_Spec_Sheet__c gss2 = new General_Spec_Sheet__c(
       
                            name = 'General Spec Sheet',
                            Opportunity__c = op.id,
                            Customer_Account__c = a.id,
                            Update_Invoice_Billing_Address__c = 'Yes',
                            Invoice_to_street__c = '1232 SW Broadway',
                            Invoice_to_City__c = 'Anytown',
                            Invoice_to_State__c = 'AnyState',
                            Invoice_to_Country__c = 'Canada',
                            Invoice_to_Zip_Postal_Code__c = '12345',
                            Technical_Contact__c = con.id,
                            Commercial_Contact__c = con.id,
                            e_mail__c = 'jo@doe.com',
                            phone__c = '5565656456',
                            Update_Technical_Contact_Record__c = 'yes',//Monica
                            Update_Commercial_Contact_Record__c = 'Yes',
                            update__c = 'yes',// Monica
                            Customer_Specific_Standards__c = 'No',
                            fax__c = '1234567898',
                            Generate_Firm_Budget_Quote__c = 'Budget Quote',
                            Requested_Date_to_Complete_Quote__c = date.parse('1/1/2020'));

             insert gss2;
   
        update gss2;

    General_Spec_Sheet__c gs = [select id, X3_Day_Minimum_Quote_Due_Date__c, Requested_Date_to_Complete_Quote__c from General_Spec_Sheet__c where id=:gss2.id];
     system.debug(' Status Formula Field : ' + gs.X3_Day_Minimum_Quote_Due_Date__c );
  
     System.assertequals(system.today()+3,gs.X3_Day_Minimum_Quote_Due_Date__c);

I am still not able to retrieve the formula value. How do I hardcode a value in the formula field?

Thank you.

Vinita_SFDCVinita_SFDC
Hi,

My mistake, you can not hard code formula field value from apex. What is being calculated in the formula field? Please make sure that the fields on which formula is biuld, are inserted. Also set all fields that are used in calculation prior to the insert.