I am trying to test my controller extension, Although the final score coverage hit into 100% but when i checked my tests log in my dev console i got Error.
This is the ERROR Message:
System.DmlException: Insert failed. First exception on row 0 with id 0010o00002DZ5DiAAL; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]
Here is my Test Class Code:
@isTest
public class AcountControllerExtensionTest {
@isTest static void verifyAccSave(){
//Create dummy account for controller
Account acc = new Account();
//call the current page for testing
Test.setCurrentPage(Page.NewAccountAndContact);
//create a standard controller and pass the dummy account controller
ApexPages.StandardController accountController = new ApexPages.StandardController(acc);
//Get the Standard Controller ang pass it to controller extension
AccountControllerExtension ace = new AccountControllerExtension(accountController);
//Start the Test
Test.startTest();
ace.acct.Name = 'Testing';
ace.cont.AccountId = ace.acct.Id;
ace.cont.LastName = 'Last Name';
ace.cont.Email = '[email protected]';
ace.save();
PageReference redPage = ace.save();
Test.stopTest();
//End Test
//Verify using assertion
Account verifyAccountInsert = [SELECT Id FROM Account where Id =: ace.acct.Id];
System.assert(verifyAccountInsert.Id != NULL);
//Verify if it's redirect to the account detailed page
System.assertEquals('/'+verifyAccountInsert.Id, redPage.getUrl());
}
}
And here is my Controller Extension:
public class AccountControllerExtension {
public final Account acct {get;set;}
public Contact cont {get;set;}
public AccountControllerExtension(ApexPages.StandardController std){
this.acct = (Account)std.getRecord();
this.cont = new Contact();
}
public PageReference save(){
//Insert the account
insert acct;
//Pass the Billing address to Contact Mailing Address if the Contact is not empty
if(cont != NULL){
cont.MailingStreet = acct.BillingStreet;
cont.MailingCity = acct.BillingCity;
cont.MailingState = acct.BillingState;
cont.MailingPostalCode = acct.BillingPostalCode;
cont.MailingCountry = acct.BillingCountry;
cont.AccountId = acct.Id;
cont.Type__c = 'Subscriber';
insert cont;
}
//Redirect to the Record Detailed Page
PageReference redirectPage = new PageReference('/' + acct.Id);
redirectPage.setRedirect(true);
return redirectPage;
}
}
I think In my test Class is it needs to add first the account before the contact but in my controller extension I put the insert Account and Contact in the same method. Any help please?