+ Start a Discussion
wixxeywixxey 

Error in test Code- System.DmlException: Insert failed. First exception

I am writing a test code for the Class but it is generating this error

System.DmlException: Insert failed. First exception on row 0 with id 0039000000NoNCHAA3; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]

Stack TraceClass.newContact.save: line 10, column 1
Class.newContact.testNewContact: line 30, column 1

 

public class newContact {
    public Contact con {get;set;}
    
    public newContact(ApexPages.StandardController c) {
            
            con = (Contact)c.getRecord();
            con.AccountId = ApexPages.currentPage().getParameters().get('pid');
    }
     public PageReference save(){
       insert con;
       
       return new PageReference('/index/index?id='+con.AccountId); 
    }
    
    public static testMethod void testNewContact(){
         PageReference pageRef = Page.newContact;
         Test.setCurrentPageReference(pageRef);
         
        Account a=new account();
        a.Name = 'Test Name';
        insert a;
        
        Contact con = new Contact(Email =  'test@test.com', LastName = 'Tester'); 
        con.Type__c = 'Customer Admin';
        con.accountid = a.id;
        insert con;
        
        ApexPages.StandardController sc = new ApexPages.standardController(con);
        newContact nC = new newContact(sc);
        PageReference pr = nC.save();
    }
}

 

 

Best Answer chosen by Admin (Salesforce Developers) 
Bhawani SharmaBhawani Sharma
remove
insert con;

line from your test class and you are all set.

All Answers

Bhawani SharmaBhawani Sharma
remove
insert con;

line from your test class and you are all set.
This was selected as the best answer
wixxeywixxey

Thanx buddy that works for me ...