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
Varun TejaVarun Teja 

How to write test class for apex controller class

Plase help me on test class.Thanks in advance



public class AccountSubmitPageController {
    
    public Account acount{get; set;}
    public Contact contct{get; set;}
    public Opportunity oportunity{get; set;}
    public Case casse{get; set;}

    public List<Contact> contactList{get; set;}
    public List<Opportunity> OppoList{get; set;}
    public boolean disableContact{get; set;}
    public boolean disableOpportunity{get; set;}
    
    public AccountSubmitPageController(ApexPages.standardController controller){  
        acount = new Account();
        contct = new Contact();
        oportunity= new Opportunity();
        casse=new Case();
        contactList=new List<Contact>();
        OppoList=new List<Opportunity>();
        disableContact=false;
        
    }


    public PageReference save() {
        //System.debug('------ Account----'+acount);
        insert acount;
        PageReference bp = new PageReference('/apex/ContactSubmitPage');
        bp.setRedirect(false);
        return bp;
        
    }
    
    public PageReference addMoreContacts() {
        contct.AccountId=acount.Id;
        if (!contactList.contains(contct)) {
             contactList.add(contct);
        }
        contct=new Contact();
        disableContact=true;
        PageReference pageref = new PageReference('/apex/ContactSubmitPage');
        pageref.setRedirect(false);
        return pageref;
    }
    
    public PageReference dontWantContact() {
        PageReference bp = new PageReference('/apex/OpportunitySubmitPage');
        bp.setRedirect(false);
        return bp;
    }
    public PageReference submitContact() {
        contct.AccountId=acount.Id;
        if (!contactList.contains(contct)) {
            contactList.add(contct);
        }
        if(contactList.size()>0){
            //System.debug('------ contactList----'+contactList);
            insert contactList;
        }
        
        PageReference pr = new PageReference('/apex/OpportunitySubmitPage');
        pr.setRedirect(false);
        return pr;
        
    }
    
    public PageReference addMoreOpportunities() {
        
        oportunity.AccountId=acount.Id;

        if (!OppoList.contains(oportunity)) {
            OppoList.add(oportunity);
        }
        oportunity=new Opportunity();
        disableOpportunity=true;
        PageReference pageref = new PageReference('/apex/OpportunitySubmitPage');
        pageref.setRedirect(false);
        return pageref;
    }
    
       public PageReference dontWantOpportunity() {
        PageReference bp = new PageReference('/apex/CaseSubmitPage');
        bp.setRedirect(false);
        return bp;
    }
    
    public PageReference submitOpportunity() {
        oportunity.AccountId=acount.Id;
        if (!OppoList.contains(oportunity)) {
            OppoList.add(oportunity);
        }
        if(OppoList.size()>0){
            //System.debug('------ OppoList----'+OppoList);
            insert OppoList;
        }
        PageReference pr = new PageReference('/apex/CaseSubmitPage');
        pr.setRedirect(false);
        return pr;
    }
    
    public PageReference caseConfirm() {
        casse.AccountId=acount.Id;
        insert casse;
        Case cs=[select Id,CaseNumber from Case where AccountId=:acount.Id];
        //System.debug('------ casse.CaseNumber----'+cs.CaseNumber);
        //System.debug('------ casse.CaseId----'+cs.Id);
        PageReference pr = new PageReference('/apex/ListAllSubmitPage?caseNumbr='+cs.CaseNumber+'&caseIds='+cs.Id);
        pr.setRedirect(false);
        return pr;
    }
    
        public PageReference done() {
        acount = new Account();
        PageReference pageref = new PageReference('/apex/AccountSubmitPage');
        pageref.setRedirect(false);
        return pageref;
    }
    
        public PageReference nextToOpportunity() {
        PageReference bp = new PageReference('/apex/OpportunitySubmitPage');
        bp.setRedirect(false);
        return bp;
    }
    
           public PageReference nextToCase() {
        PageReference bp = new PageReference('/apex/CaseSubmitPage');
        bp.setRedirect(false);
        return bp;
    }
        public PageReference backToContact() {
        PageReference bp = new PageReference('/apex/ContactSubmitPage');
        bp.setRedirect(false);
        return bp;
    }
 }
Raj VakatiRaj Vakati
@istest
public class apexTest
{
    static testmethod void testM(){
        
        Test.StartTest(); 
        
        Account a = new Account();
        a.Name  = 'Test Account';
        insert a;
        
     


        Opportunity opp = new Opportunity();
        opp.Name='NewOpp';
        opp.AccountId=a.Id;

        opp.StageName='Prospecting';
        opp.CloseDate=Date.today().addDays(10);

        insert opp;

        
        
        case ccc =new Case(
            AccountId = a.Id,
            Type='Web',
            Origin='Web',
            Status='New',
          );
        
        insert ccc;
        
        
        ApexPages.StandardController sc = new ApexPages.StandardController(a);
        AccountSubmitPageController testMerch = new AccountSubmitPageController (sc);
        
        PageReference pageRef = Page.page1; 
        pageRef.getParameters().put('id',a.Id);
        Test.setCurrentPage(pageRef);
        testMerch.addMoreContacts();
        
        
        testMerch.dontWantContact();
        testMerch.submitContact();
        testMerch.addMoreOpportunities();
        testMerch.dontWantOpportunity();
        testMerch.submitOpportunity();
        testMerch.caseConfirm();
        testMerch.done();
        testMerch.nextToOpportunity();
        testMerch.nextToCase();
        testMerch.backToContact();
        
        testMerch.save();
        
        Test.StopTest();
        
    }
}

 
Varun TejaVarun Teja
Giving error as "Class.AccountSubmitPageController.submitContact: line 58, column 1
Class.AccountSubmitPageControllerTest.testM: line 35, column 1"
Raj VakatiRaj Vakati
Can you give me what is error .. 
Varun TejaVarun Teja
System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [LastName]: [LastName]
Varun TejaVarun Teja
I have added below code .Even though I'm getting error
        Contact con= new Contact();
        con.LastName='Nag';
        con.FirstName='Arjun';
        con.AccountId=a.Id;
Raj VakatiRaj Vakati
give me complete code and see what error you are getting now 
 
Varun TejaVarun Teja
@isTest
public class AccountSubmitPageControllerTest {
    
    static testmethod void testM(){
        
        Test.StartTest(); 
        
        Account a = new Account();
        a.Name  = 'Test Account';
        insert a;
        
        Contact con= new Contact();
        con.LastName='Nag';
        con.FirstName='Arjun';
        con.AccountId=a.Id;
        
        insert con;
 
        Opportunity opp = new Opportunity();
        opp.Name='NewOpp';
        opp.AccountId=a.Id;

        opp.StageName='Prospecting';
        opp.CloseDate=Date.today().addDays(10);

        insert opp;
   
        case ccc =new Case(AccountId = a.Id,Type='Web',Origin='Web',Status='New');
        
        insert ccc;
        
        
        ApexPages.StandardController sc = new ApexPages.StandardController(a);
        AccountSubmitPageController testMerch = new AccountSubmitPageController (sc);
        
        PageReference pageRef = Page.ContactSubmitPage; 
        pageRef.getParameters().put('id',a.Id);
        Test.setCurrentPage(pageRef);
        testMerch.addMoreContacts();
        
        testMerch.dontWantContact();
        testMerch.submitContact();
        testMerch.addMoreOpportunities();
        testMerch.dontWantOpportunity();
        testMerch.submitOpportunity();
        testMerch.caseConfirm();
        testMerch.done();
        testMerch.nextToOpportunity();
        testMerch.nextToCase();
        testMerch.backToContact();
        
        testMerch.save();
        
        Test.StopTest();
        
    }

}



Getting erro: System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [LastName]: [LastName]

Stack trace: Class.AccountSubmitPageController.submitContact: line 58, column 1
Class.AccountSubmitPageControllerTest.testM: line 42, column 1
Varun TejaVarun Teja
Below are my multiple VF pages

AccountSubmitPage:
-----------------

<apex:page standardController="Account" extensions="AccountSubmitPageController">

    <apex:form id="myform" styleClass="myFormStyle">
        <apex:pageBlock title="Insert Account  Record" id="myPageBlock">
            <apex:pageMessages ></apex:pageMessages>
            <apex:pageBlockSection id="myPageBlockSec" columns="2">
                <apex:inputField value="{! acount.OwnerId }" />
                <apex:inputField value="{! acount.Name }" />
                <apex:inputField value="{! acount.Type }" />
                <apex:inputField value="{! acount.Industry }" />
                <apex:inputField value="{! acount.AnnualRevenue }" onkeypress="return inputLimiter(event,'Numbers');" required="true"/>
                <apex:inputField value="{! acount.NumberOfEmployees }" onkeypress="return inputLimiter(event,'Numbers');"/>
                <apex:inputField value="{! acount.Phone }" id="txtMobId" onchange="phonenumber()"/>
                <div id="err1"></div>
                <apex:inputField value="{! Account.Rating }" />
                <!--<center><apex:commandButton action="{! save }" value="Save" /></center>-->
            </apex:pageBlockSection>
            <apex:pageBlockButtons location="bottom">
         <apex:commandButton action="{! save }" value="Save" styleClass="buttonStyle" style="margin-left: 200px;"/>
    </apex:pageBlockButtons>
        </apex:pageBlock>
        <script>
        function inputLimiter(e,allow) {
            var AllowableCharacters = '';

            if (allow == 'Letters'){AllowableCharacters=' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';}
            if (allow == 'Numbers'){AllowableCharacters='1234567890';}
            if (allow == 'NameCharacters'){AllowableCharacters=' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-.\'';}
            if (allow == 'NameCharactersAndNumbers'){AllowableCharacters='1234567890 ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-\'';}
            if (allow == 'Currency'){AllowableCharacters='1234567890.';}

            var k = document.all?parseInt(e.keyCode): parseInt(e.which);
            if (k!=13 && k!=8 && k!=0){
                if ((e.ctrlKey==false) && (e.altKey==false)) {
                return (AllowableCharacters.indexOf(String.fromCharCode(k))!=-1);
                } else {
                return true;
                }
            } else {
                return true;
            }
        }
        
        function phonenumber() {
            document.getElementById("err1").innerHTML="";
            var phone=document.getElementById('{!$Component.myform.myPageBlock.myPageBlockSec.txtMobId}').value;
            var letters = '/^[A-Za-z]+$/';
            if(phone.length!=10 || phone.match(letters))
                document.getElementById("err1").innerHTML="Phone must be 10 digits long OR Can not contain Letters.";
        }
        </script>
    </apex:form>
</apex:page>

ContactSubmitPage:
------------------
<apex:page standardController="Account" extensions="AccountSubmitPageController" id="mypage">

    <apex:form rendered="true" id="myformc">
        <apex:pageBlock title="Insert Contact Record" id="myPageBlockc" >
            
            <apex:pageBlockSection id="Conlist">
                <center><apex:outputText label="Total No Of Contacts added till Now" id="total" value="{!contactList.size}" style="font-size: 15px;color:red;"/></center>
            </apex:pageBlockSection>
            <apex:pageBlockSection id="myPageBlockSecc">
                <apex:outputField value="{!acount.Name}" />
               </apex:pageBlockSection>
            <apex:pageBlockSection id="myPageBlockSec" columns="1">
                <apex:outputLabel style="font-size: 13px;margin-left: 170px;font-weight:700">Personal Details</apex:outputLabel>
            <apex:inputField value="{! contct.FirstName }" required="true"/>
                <apex:inputField value="{! contct.LastName }" required="true"/>
                <apex:inputField value="{! contct.Birthdate }" />
                 <apex:inputField value="{! contct.Email }" required="true"/>
                <apex:inputField value="{! contct.HomePhone }" id="txtMobIds" onchange="phonenumber()" required="true"/>
                <div id="err1"></div>
            </apex:pageBlockSection>
            <apex:pageBlockSection id="myPageBloc" columns="1">
                <apex:outputLabel style="font-size: 13px;margin-left: 170px;font-weight:700">Other Details</apex:outputLabel>
                 <apex:inputField value="{! contct.Description }" style="width: 360px; height: 40px"/>
                <apex:inputField value="{! contct.Level__c }" />
             </apex:pageBlockSection>
            <apex:pageblockButtons location="bottom">
                <apex:commandButton id="conbtn" action="{! addMoreContacts }" value="Add More Contacts" onclick="disableOpportunity(this);"/>
                <apex:commandButton id="oppbtn" action="{! dontWantContact }" disabled="{! disableContact }" immediate="true" value="I don't want to create contact" />
                <apex:commandButton action="{! submitContact }" value="Submit Contact's" />
                <apex:commandButton action="{! nextToOpportunity }" value="Next" immediate="true"/>
            </apex:pageblockButtons>
        </apex:pageBlock>
        <script>
        
            function disableOpportunity() {
            var btn = document.querySelector("[id$='conbtn']");
            var btn1 = document.querySelector("[id$='oppbtn']");
            btn1.className = 'btn1 btnDisabled';
            btn1.disabled = 'disabled';
                //document.getElementById("btn").disabled = false
            return false;
        }
        
        function inputLimiter(e,allow) {
            var AllowableCharacters = '';

            if (allow == 'Letters'){AllowableCharacters=' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';}
            if (allow == 'Numbers'){AllowableCharacters='1234567890';}
            if (allow == 'NameCharacters'){AllowableCharacters=' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-.\'';}
            if (allow == 'NameCharactersAndNumbers'){AllowableCharacters='1234567890 ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-\'';}
            if (allow == 'Currency'){AllowableCharacters='1234567890.';}

            var k = document.all?parseInt(e.keyCode): parseInt(e.which);
            if (k!=13 && k!=8 && k!=0){
                if ((e.ctrlKey==false) && (e.altKey==false)) {
                return (AllowableCharacters.indexOf(String.fromCharCode(k))!=-1);
                } else {
                return true;
                }
            } else {
                return true;
            }
        }
        
        function phonenumber() {
            document.getElementById("err1").innerHTML="";
            var phone=document.getElementById('{!$Component.myformc.myPageBlockc.myPageBlockSec.txtMobIds}').value;
             var letters = '/^[A-Za-z]+$/';
            if(phone.length!=10 || phone.match(letters))
                document.getElementById("err1").innerHTML="Phone must be 10 digits long OR Can not contain Letters.";
        }
        
      
        </script>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> 
<span id="hideMyParent"></span> 
<script type="text/javascript"> 
$(document).ready(function() { 
var startYear=1900; 
var endYear=2018; 
var optionsString=''; 
if(startYear<endYear)

for(i=startYear;i<endYear+1;i++)

optionsString += "<option value=\""+i+"\">"+i+"</option>"; 

$('#calYearPicker').html(optionsString); 
} $('#sidebarDiv #hideMyParent').parent().parent().hide(); 
});
</script>
    </apex:form>
</apex:page>


OpportunitySubmitPage:
----------------------
<apex:page standardController="Account" extensions="AccountSubmitPageController">

    <apex:form rendered="true">
        <apex:pageBlock title="Insert Opportunity Record">
            
            <apex:pageBlockSection >
                <center><apex:outputText label="Total No Of Opportunities added till Now" id="total" value="{!OppoList.size}" style="font-size: 15px;color:red;"/></center>
            </apex:pageBlockSection>
            <apex:pageBlockSection >
                <apex:outputField value="{!acount.Name}" />
                <apex:inputField value="{! oportunity.Name }" />
                <apex:inputField value="{! oportunity.Amount }" />
                <apex:inputField value="{! oportunity.Type }" required="true"/>
                <apex:inputField value="{! oportunity.CloseDate }" />
                <apex:inputField value="{! oportunity.StageName }" />
                <apex:inputField value="{! oportunity.LeadSource }" />
                <apex:inputField value="{! oportunity.Description }" />
              </apex:pageBlockSection>
            <apex:pageblockButtons location="bottom">
                <apex:commandButton action="{! backToContact }" value="Back" immediate="true"/>
                <apex:commandButton action="{! addMoreOpportunities }" value="Add More Opportunities" />
                <apex:commandButton action="{! dontWantOpportunity }" disabled="{!disableOpportunity}" immediate="true" value="I don't want to create Opportunity" />
                <apex:commandButton action="{! submitOpportunity }" value="Submit Opportunity's" />
                <apex:commandButton action="{! nextToCase }" value="Next" immediate="true"/>
            </apex:pageblockButtons>
        </apex:pageBlock>
    </apex:form>
</apex:page>
Raj VakatiRaj Vakati
I believe the issue is the order of methods we are calling in the test class .. Can you call them in the order how it will be executed 

testMerch.XXXX methods should be in the same order how it will work from the UI 
 
Varun TejaVarun Teja
Thanks for suggestion.Still giving error as "System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Name]: [Name]"..