I am trying to create a test data for coverage. The field is a formula field and it has a master-detail relationship with another object, then I create a recode in the object. but how can I reference the field in the detail object? I am getting an error:

Field is not writeable

How Can I do that? The PLS_Code__c is a formula field and formulae are: Positioner_Limit_Switch__r.Code__c

    VWC_Positioner_LimitSwitch__c  PLSObj = new VWC_Positioner_LimitSwitch__c();

    PLSObj.Code__c = '2HPB';

    PLSObj.Description__c   = 'This is test data.';

    insert PLSObj;        

    VWC_PLS_Combination__c pls_Combination = new VWC_PLS_Combination__c();        

    pls_Combination.Price__c = 123;        

    pls_Combination.Positioner_Limit_Switch__r.Code__c = PLSObj.id;        
    insert pls_Combination;       
    instance.selectedPositioner = '2HPB';`
  • once you insert pls_Combination, you must be able to access the formula value.
    – Ashwani
    Apr 6, 2017 at 8:25

2 Answers 2


Your formula field is referencing the Code__c field of the VWC_Positioner_LimitSwitch__c object linked to your VWC_PLS_Combination__c object using its Positioner_Limit_Switch__c field.

By definition, a formula field is calculated. Once your VWC_Positioner_LimitSwitch__c object will be linked to your VWC_PLS_Combination__c object, the field will be calculated.

So you only have to replace your line:

pls_Combination.Positioner_Limit_Switch__r.Code__c = PLSObj.id;


pls_Combination.Positioner_Limit_Switch__c = PLSObj.id;
  • You saved my Life, I was stuck there for many hours!
    – sami ullah
    Apr 6, 2017 at 13:17
  • Glad I could help @samiullah ! Apr 6, 2017 at 13:18

Please check this new test data factory library Apex Test Kit: https://github.com/ApexTestKit/ApexTestKit

Your scenario can be transformed like this, and relationship is automatically assigned for you:

    .fields(new Map<String, Object> {
        'Code__c' => '2HPB'
        'Description__c' => '{!lorem.sentence}' // generate dummy text, can be omitted
        .fields(new Map<String, Object> {
            'Price__c' => 123

With ApexTestKit 1.0, it focuses on data generation only. If it is getting popular and wanted by the community, 2.0 will provide BDD functions.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .