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
Ashok S 7Ashok S 7 

how can i write test class for my controller

Hai guys.

When i am writng the the testclass for following controller it is displaying the error.
public class Action_Function_Controller 
   public Account acobj{get;set;}
   pagereference pag = null;
   public Action_Function_Controller()
       acobj = new Account();
    public pagereference save()
       // creating if condidtion
       if( != '')
          insert acobj;
           //creating a error message
           ApexPages.Message msg = new ApexPages.Message(ApexPages.SEVERITY.ERROR,'Error:Enter Name');
        //Creting another if condition
        if( != null)
          // Send the user to the detail page for the new account.
          pag = new pagereference('/';
        return pag;

public class  ActionFunctionControllerTest
    public static testmethod void testfunction()
          //inserting record into the account object
          Account acc = new Account();
 = 'Test Account';
          acc.industry = 'Accounts';
          insert acc;
        //using the page reference
        pagereference pg = page.Action_Function_VF_PAge;
        //calling controller class
        Action_Function_Controller afc = new Action_Function_Controller();
        //calling the variables into testclass
        if( !='')
           insert acc;
when i run the test class following are occured
System.DmlException: Insert failed. First exception on row 0 with id 00128000008E4KRAA0; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]
Please help me any one.
Alexander TsitsuraAlexander Tsitsura
Hi Ashok,

Problem is that you can try to insert record with id. 
There u insert account
//inserting record into the account object
Account acc = new Account(); = 'Test Account';
acc.industry = 'Accounts';
insert acc;

and here you ansert account too
if( !='')
    insert acc;

Maybe it's help write upsert instead of insert.

As a common practice, if your question is answered, please choose 1 best answer. 
But you can give every answer a thumb up if that answer is helpful to you.

Ya - it's your second insert acc; that is failing.  After the first Insert Acc; - you got an ID for the record.