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
Sebastian PageSebastian Page 

I am not getting code coverage showing error

Hi  Expert ,

I am updating  contact field from user object using schedule class. and My apex class working fine but  I am getting error while test class running and also i am not getting code coverage. kindly assist me where i am doing mistake. 
Error is showing -  "System.DmlException: Insert failed. First exception on row 0 with id 0011F00000oLXWlQAO; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]".
 
public class Global_UserLastLoginController implements Schedulable{
    public void execute(SchedulableContext SC)
    {
        Global_UserLastLoginController.getLastLogin();
       // Global_UserLastLoginController.getUpdateLicence();
    }
    
    public static void getLastLogin()
    {
      List<Contact> getupdateContact=new List<contact>();
        Map<String,Datetime> mapcontact= new Map<String,Datetime>();
        List<User> getUserLst=[select Contactid,lastLoginDate from user where contactId!=null and isactive=true and AccountId='0011F00000ml9jh']; 
        for(User u:getUserLst)
        {
           mapcontact.put(u.ContactId, u.lastLoginDate);
        }
        for(Contact con:[select id,Last_Login__c from contact where accountId='0011F00000ml9jh'])
        {
            con.Last_Login__c=mapcontact.get(con.id);
            getupdateContact.add(con);
        }
        
        update getupdateContact;

    }
    
       

}

and My Test class is
 
@isTest
public class Global_UserLastLoginUpdateTest {
    @isTest
    public Static void UnitlastLoginTest()
    {
        String CRON_EXP = '0 15 * * * ?';
          Test.startTest();
        
        Account acc=new Account();
            acc.name='Pasadena';
        insert acc;
        
       acc.Enable_CaseCreationTrigger__c=true;
        acc.Account_Case_RecType_Validation__c='Pasadena';
        insert acc;
        system.assertEquals(True, acc.Enable_CaseCreationTrigger__c);
        Contact con = new Contact(AccountId=acc.Id,LastName='test');
        insert con;
        
       String jobId = System.schedule('Global_UserLastLoginUpdateTest',  CRON_EXP, new Global_UserLastLoginController());
            CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE id = :jobId];
            System.assertEquals(CRON_EXP, ct.CronExpression);
            System.assertEquals(0, ct.TimesTriggered);
        test.stopTest();
        } 
    }

 
Vishwajeet kumarVishwajeet kumar
Hello,

it looks like code is trying to insert acc twice here  : 

Account acc=new Account();
acc.name='Pasadena';
insert acc;

acc.Enable_CaseCreationTrigger__c=true;
acc.Account_Case_RecType_Validation__c='Pasadena';
insert acc;     // Update it to - update acc;  

Thanks.