Sergey
Sergey

Reputation: 49758

Salesforce Formula Field always equals null in Apex code

I have a formula field "Asset MRR" defined for the Asset object.
The value of this field is defined to always equal 100: enter image description here

But when I try to access "Asset MRR" field in Apex, asset.Asset_MRR__c equals null for some reason:

static testMethod void assetTriggerTest2() {
        Account account = new Account(Name='SFDC Account');
        insert account;

        Asset asset = new Asset(Name='asset name', AccountId = account.Id);
        insert asset;

        // System.AssertException: Assertion Failed: Expected: null, Actual: 100
        System.assertEquals(asset.Asset_MRR__c, 100); 
    }

While in Salesforce interface the value of asset.Asset_MRR__c is 100, like it's supposed to be: enter image description here

Why does asset.Asset_MRR__c equal null in Apex? Why isn't it 100?

Upvotes: 1

Views: 4617

Answers (1)

Psymn
Psymn

Reputation: 382

You need to re-query for the record and include the field.

Asset asset = [Select ID, Name, Asset_MMR__c from Asset where id =: asset.id limit 1][0];

System.assertEquals(asset.Asset_MRR__c, 100);

Upvotes: 4

Related Questions