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
Ertyq MrskErtyq Mrsk 

INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id] Error When Running Test Class

I've been trying to run my test class via Visual Studio Code, but I get the following error message:

INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]

Deployment to org is successful though, but it keeps displaying such message when I run it.

As for the controller, it just inserts a new custom object record.

Meanwhile, following are both controller, TestDataFactory, test class I've been working on:

CustObj1Controller
public with sharing class CustObj1Controller {
    
    @AuraEnabled
    public static CustObj1__c createCustomObj1(CustObj1__c newCustObj1){
        insert newCustObj1;
        return newCustObj1;    
    }
   
}
TestDataFactory
@isTest
public with sharing class TestDataFactory {
    public static List<CustObj1__c> createCustObj1(Integer count, Boolean performDML) {
        List<CustObj1__c> custObj1List = new List<CustObj1__c>();
        for(Integer i=0; i < count; i++) {
            CustObj1__c custObj1 = new CustObj1__c();
            custObj1.Field1__c = 'this is a sample field value' + i;
            custObj1List.add(custObj1);
        }    
        if(performDML) {
            insert custObj1List;
        }
        return custObj1List;
    }
}
CustObj1ControllerTest
@isTest
private class CustObj1ControllerTest {
    @TestSetup
    static void testSetup(){
        Test.startTest();
        List<CustObj1__c> custObj1List =    TestDataFactory.createCustObj1(1, false);    
        CustObj2__c custObj2 = new CustObj2__c();
        custObj2.CustObj1__c = custObj1List[0].Id;
        custObj2.Field1__c = 'Field1';
        custObj2.Field2__c = 'Field2'; 
        insert custObj2; 
        Test.stopTest();
    }
    @isTest static void testCustObj1() {
        List<CustObj2__c> custObj2List  =  [SELECT CustObj1__c FROM CustObj2__c];
        System.assertEquals(true,custObj2List.size()>0);
        CustObj1Controller.createCustomObj1(custObj2List[0]);
    }
}
Hoping someone could help me on this.
 
ShirishaShirisha (Salesforce Developers) 
Hi Ertyq,

Greetings!

I can see that you are trying to use the Id before inserting the records in the test class as below:

custObj2.CustObj1__c = custObj1List[0].Id;

I would suggest you to double check,if it has any value:TestDataFactory.createCustObj1(1, false);

Kindly mark it as best answer if it helps so that it can help others in the future.

Warm Regards,
Shirisha Pathuri