[SalesForce] Field is not writeable: CAM_Members__c.Affiliate_State__c

My compiler says that this field is not writeable:

Field is not writeable: CAM_Members__c.Affiliate_State__c

I have this class

static testMethod void AffliateTest(){

    SS_Data__c ns = new SS_Data__c();
    SS.Name = 'test SS';
    insert ss;


   Account a = new Account();
   a.name = 'Test Account Affliate';
   a.BillingState = 'WA';
   insert a;

   contact c = new contact();
   c.lastname = 'Test';
   insert c;


   Relationship__c rc  = new Relationship__c();
   rc.Account__c = a.id;
   rc.Contact__c = c.id;
   rc.Start_Date__c = system.today();

   insert rc;


   CAM_Members__c mem = new CAM_Members__c();
   mem.Name = 'test VM';
   mem.SS_Data__c = ss.Id;
   mem.Member_Name__c = '0034000001TTfQW';
   mem.Member_ID__c = '9999';
   mem.Relationship__c = rc.Id;
   insert mem;

    CAM_Members__c insertedRecord = [
    SELECT Affiliate_State__c FROM CAM_Members__c WHERE Id = :mem.Id
    ];
   system.assertEquals(a.BillingState, insertedRecord.Affiliate_State__c, 'WA');


}

The field has this formula:

Relationship__r.Account__r.BillingState

What am I doing wrong? How can I fix it? My Problem now is it has no coverage try the above Affliate State = WA wherein it should be covered but not working

Best Answer

You cannot create or update the value for formula fields. The only way to control their value is to set up the related data in a way that it calculates what you want. In this case, you would need to set the parent Relationship__c and then insert the record:

mem.Relationship__c = rc.Id;
insert mem;

CAM_Members insertedRecord = [
    SELECT Affiliate_State__c FROM CAM_Members__c WHERE Id = :mem.Id
];
system.assertEquals(a1.BillingState, insertedRecord.Affiliate_State__c, '<message_here>');

That said, you shouldn't test the output of your formulas with a unit test. You should use regression testing to verify their behavior. Unit tests on configuration aspects which can be easily changed are very brittle and will harm your org health in the long run.

Related Topic