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.