+ 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:

public with sharing class CustObj1Controller {
    public static CustObj1__c createCustomObj1(CustObj1__c newCustObj1){
        insert newCustObj1;
        return newCustObj1;    
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;
        if(performDML) {
            insert custObj1List;
        return custObj1List;
private class CustObj1ControllerTest {
    static void testSetup(){
        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; 
    @isTest static void testCustObj1() {
        List<CustObj2__c> custObj2List  =  [SELECT CustObj1__c FROM CustObj2__c];
Hoping someone could help me on this.
ShirishaShirisha (Salesforce Developers) 
Hi Ertyq,


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