+ Start a Discussion

Test class for this class

Hi Experts,

Could any one help me out by writing test class for this class. please.

 trillo global params is the parent of all the remainging object what ever i wrote below.

tRIIO_Global_Params__c(parent)---tRIIO_Contract__c(child )---tRIIO_Project__c(child)--tRIIO_Works_Order__c(child)---tRIIO_Activity__c(child)--tRIIO_Project_Closure_Session__c

public with sharing class tRIIO_NewProjectClosureSession_Exten

02 {

03     public static tRIIO_Activity__c activity;

04     public static List<tRIIO_Activity__c> listActivity;

05     public static tRIIO_Works_Order__c worksOrder;

06     public static List<tRIIO_Works_Order__c> lstWorksOrder;

07     private static String actID;

08     public tRIIO_Project_Closure_Session__c PCS {get;set;}

09     static

10     {

11              String fullURL = ApexPages.currentPage().getUrl();

12              String[] reqURL = fullURL.split('&');

13              String[] reqId = reqURL[1].split('=');

14              System.debug('@#@# URLs Full URL = '+ fullURL+'  Split URL = '+reqURL[1]+'  reqID = '+ reqId[1]);

15              if([SELECT count() FROM tRIIO_Activity__c WHERE Id =:reqId[1]] == 1)

16                 listActivity = [SELECT id, Name,Works_Order__c from tRIIO_Activity__c Whereid=:reqId[1]];

17              else

18                 lstWorksOrder = [SELECT id,Name from tRIIO_Works_Order__c where id=:reqId[1]];

19     }

20     public tRIIO_NewProjectClosureSession_Exten(ApexPages.StandardController controller) {

21             PCS = (tRIIO_Project_Closure_Session__c)controller.getRecord();

22           try{

23             if(listActivity.size() > 0 )

24             {

25                 PCS.tRIIO_Works_Order__c = listActivity[0].Works_Order__c;

26                 PCS.Activity_Ref__c = listActivity[0].id;

27             }

28             else if(lstWorksOrder.size() > 0 )

29             {

30               PCS.tRIIO_Works_Order__c = lstWorksOrder[0].id;

31             } 

32           }catch(Exception e){}

33     }

34 }
Follow the below approach for writing test class for the standard controller extension
//Create your test data for the test class 
Test.setCurrentPage(Page.YOUR_PAGE); //Mention the page where you use the extension class

//Instantiate object of "ApexPages.StandardController" by passing object
ApexPages.StandardController stdController = new ApexPages.StandardController(acct); //acct - Test data
//Now, create Object of your Controller extension by passing object of standardController
YOUR_Extension ext = new YOUR_Extension(stdController);
//Here you can test all public methods defined on Extension "ext"
//..... your code
//Finish Test

Amit Chaudhary 8Amit Chaudhary 8
Please create the test class like below 
public class tRIIO_NewProjectClosureSession_ExtTest 
	static testMethod void testMethod1() 
		Account testAccount = new Account();
		testAccount.Name='Test Account' ;
		insert testAccount;

		tRIIO_Global_Params__c gp = new tRIIO_Global_Params__c();
		gp.Name ='test GP';
		insert gp ;
		tRIIO_Contract__c tRC = new tRIIO_Contract__c();
		// Add all field here
		insert tRC;
		tRIIO_Project__c tRP = new tRIIO_Project__c();
		//tRP Add all field here
		insert tRP;
		tRIIO_Works_Order__c tRWO = new tRIIO_Works_Order__c();
		// Add all field here
		insert tRWO;

		tRIIO_Activity__c tRIio = new tRIIO_Activity__c();
		//Add all field here
		insert tRIio;

		tRIIO_Project_Closure_Session__c tRPCS = new tRIIO_Project_Closure_Session__c();
		//Add all field here
		insert tRPCS;
		ApexPages.StandardController sc = new ApexPages.StandardController(tRPCS);
		myControllerExtension testAccPlan = new myControllerExtension(sc);

		PageReference pageRef = Page.AccountPlan; // Add your VF page Name here
		pageRef.getParameters().put('id', String.valueOf(tRPCS.Id));


Please check below blog for more information on test classes

Please follow below salesforce Best Practice for Test Classes :-

1. Test class must start with @isTest annotation if class class version is more than 25
2. Test environment support @testVisible , @testSetUp as well
3. Unit test is to test particular piece of code working properly or not .
4. Unit test method takes no argument ,commit no data to database ,send no email ,flagged with testMethod keyword .
5. To deploy to production at-least 75% code coverage is required 
6. System.debug statement are not counted as a part of apex code limit.
7. Test method and test classes are not counted as a part of code limit
9. We should not focus on the  percentage of code coverage ,we should make sure that every use case should covered including positive, negative,bulk and single record .
Single Action -To verify that the the single record produces the correct an expected result .
Bulk action -Any apex record trigger ,class or extension must be invoked for 1-200 records .
Positive behavior : Test every expected behavior occurs through every expected permutation , i,e user filled out every correctly data and not go past the limit .
Negative Testcase :-Not to add future date , Not to specify negative amount.
Restricted User :-Test whether a user with restricted access used in your code .10. Test class should be annotated with @isTest .
11 . @isTest annotation with test method  is equivalent to testMethod keyword .
12. Test method should static and no void return type .
13. Test class and method default access is private ,no matter to add access specifier .
14. classes with @isTest annotation can't be a interface or enum .
15. Test method code can't be invoked by non test request .
16. Stating with salesforce API 28.0 test method can not reside inside non test classes .
17. @Testvisible annotation to make visible private methods inside test classes.
18. Test method can not be used to test web-service call out . Please use call out mock .
19. You can't  send email from test method.
20.User, profile, organization, AsyncApexjob, Corntrigger, RecordType, ApexClass, ApexComponent ,ApexPage we can access without (seeAllData=true) .
21. SeeAllData=true will not work for API 23 version eailer .
22. Accessing static resource test records in test class e,g List<Account> accList=Test.loadData(Account,SobjectType,'ResourceName').
23. Create TestFactory class with @isTest annotation to exclude from organization code size limit .
24. @testSetup to create test records once in a method  and use in every test method in the test class .
25. We can run unit test by using Salesforce Standard UI,Force.com IDE ,Console ,API.
26. Maximum number of test classes run per 24 hour of period is  not grater of 500 or 10 multiplication of test classes of your organization.
27. As apex runs in system mode so the permission and record sharing are not taken into account . So we need to use system.runAs to enforce record sharing .
28. System.runAs will not enforce user permission or field level permission .
29. Every test to runAs count against the total number of DML issued in the process .

Please let us know if this post will help you

Amit Chaudhary
HI AMit,

Its thrwoing list out of bound exception : 1, in this test class 38 and in the  class 34 that ( String[] reqId = reqURL[1].split('=');)

static testMethod void myUnitTest() {
        tRIIO_Global_Params__c gp=new tRIIO_Global_Params__c(Identifier__c='SCart5');
        insert gp;
        tRIIO_Contract__c NGCont =New tRIIO_Contract__c(Name='65987',Description__c='NG East Coalition - Replacement East Midlands South',Valid_Work_Types__c='Governor',Valid_Areas__c='East Angelia',Valid_Schedule_Types__c='2');
        insert NGCont;
        tRIIO_Project__c TestProject = new tRIIO_Project__c(Contract__c=NGCont.id,Name='testProject', Ref_No__c='testRefNo', 
        Area__c='East Angelia',Type__c='Governor', Depot__c='retrettr', schedule__c='2',Cost_Centre__c='testcost');
        insert TestProject;
        tRIIO_Works_Order__c work = new tRIIO_Works_Order__c(PCP_Validated__c=null,Street__c='testStreet',Project__c=TestProject.Id,Tier__c ='Tier 3 MP',Works_Order_Number__c='12234');
        insert work;
        tRIIO_Activity__c TestNotice = new tRIIO_Activity__c(Works_Order__c=work.id, Activity_Status__c = 'IntrR', Status__c='IntrC',Works_End_Date__c=date.today(), Location_of_works__c='1',Eastings_Start__c='454594',Northings_Start__c ='334824',NRSWA_No__c='test notice', Street__c='test street', D_42__c=True);
        insert TestNotice;
        tRIIO_Project_Closure_Session__c projClosuerSession =  new tRIIO_Project_Closure_Session__c(Closure_Type__c='SCP',tRIIO_Works_Order__c=work.id,Pack_Received_From_Field__c=Date.today());  
        insert projClosuerSession;
         PageReference pageRef = Page.tRIIO_NewProjectClosureSession;
         pageRef.getParameters().put('id', String.valueOf(projClosuerSession.Id));

        ApexPages.StandardController sc = new ApexPages.StandardController(projClosuerSession);

        tRIIO_NewProjectClosureSession_Exten testAccPlan = new tRIIO_NewProjectClosureSession_Exten(sc);
HI Amit,

i checked that object, in the new button they cloned with this vf page(https://cs23.salesforce.com/066D00000007J6O)

<apex:page standardController="tRIIO_Project_Closure_Session__c" extensions="tRIIO_NewProjectClosureSession_Exten" tabStyle="tRIIO_Project_Closure_Session__c" >
 <apex:sectionHeader title="tRIIO Project Closure Session Edit" subtitle="New tRIIO Project Closure Session"/>
   <apex:form >
     <apex:pageMessages />
      <apex:pageBlock id="PB" title="tRIIO Project Closure Session Edit">
        <apex:pageBlockButtons >
            <apex:commandButton value="Save" action="{!save}"/>
            <apex:commandButton value="Cancel" action="{!Cancel}"/>
          <apex:pageBlockSection title=" Status Information">
              <apex:inputField id="Name" value="{!PCS.Pack_Received_From_Field__c}"/>
              <apex:inputField id="con" value="{!PCS.tRIIO_Works_Order__c}"/>
              <apex:inputField id="pckLoc" value="{!PCS.Pack_location__c}"/>
              <apex:inputField id="actR" value="{!PCS.Activity_Ref__c}"/>
              <apex:inputField id="session" value="{!PCS.Session_Status__c}"/>
              <apex:inputField id="ct" value="{!PCS.Closure_Type__c}"/>
              <apex:inputField id="esri" value="{!PCS.ESRI_Live_Layer_Date__c}"/>
              <apex:outputField id="final" value="{!PCS.Final__c}"/>
              <apex:inputField id="sessno" value="{!PCS.Session_Number__c}"/>
          <apex:pageBlockSection title=" Project Closure">
              <apex:inputField id="servst" value="{!PCS.Services_Status__c}"/>
              <apex:inputField id="prst" value="{!PCS.Purge_Relight_Status__c}"/>
              <apex:inputField id="serstd" value="{!PCS.Services_Status_Date__c}"/>
              <apex:inputField id="prstd" value="{!PCS.Purge_Relight_Status_Date__c}"/>
              <apex:inputField id="serup" value="{!PCS.Services_Updated_By__c}"/>
              <apex:inputField id="prup" value="{!PCS.Purge_Relight_Updated_By__c}"/>              
              <apex:inputField id="dmsst" value="{!PCS.DMS_Status__c}"/>
              <apex:inputField id="digitStatus" value="{!PCS.Digitisation_Status__c}"/>
              <apex:inputField id="dmsstd" value="{!PCS.DMS_Status_Date__c}"/>
              <apex:inputField id="digitDate" value="{!PCS.Digitisation_Date__c}"/>
              <apex:inputField id="dmsup" value="{!PCS.DMS_Updated_By__c}"/>
              <apex:inputField id="digitUpdatedBy" value="{!PCS.Digitisation_Updated_By__c}"/>
              <apex:inputField id="redesignStatus" value="{!PCS.Re_design_Status__c}"/>
              <apex:inputField id="abnd" value="{!PCS.Abandonment_in_Pack_m__c}"/>
              <apex:inputField id="redesignStatusDate" value="{!PCS.Re_design_Status_Date__c}"/>
              <apex:inputField id="lay" value="{!PCS.Lay_in_Pack_m__c}"/>
              <apex:inputField id="redesignUpdatedBy" value="{!PCS.Redesign_Updated_By__c}"/>
              <apex:inputField id="sapWoStatus" value="{!PCS.SAP_WO_status__c}"/>
              <apex:pageBlockSectionItem />
              <apex:inputField id="dct" value="{!PCS.DCT__c}"/>
Amit Chaudhary 8Amit Chaudhary 8
Please post the new clone button code
this is the button code only what ever i sent  you,on that object button called new in that they mentioned this vf page 
Amit Chaudhary 8Amit Chaudhary 8
Step 1:- Can you please post the button Screen shot.
Step 2:- Open your VF page and send me below debug log output
System.debug('@#@# URLs Full URL = '+ fullURL+'  Split URL = '+reqURL[1]+'  reqID = '+ reqId[1]);

on the button name will be  only one button New tRiio Project Closure session

07:24:33.297 (2297555704)|SYSTEM_METHOD_ENTRY|[89]|System.debug(ANY)
07:24:33.297 (2297560271)|USER_DEBUG|[89]|DEBUG|@#@# Roll up summary flag 2 ==> true
07:24:33.297 (2297564617)|SYSTEM_METHOD_EXIT|[89]|System.debug(ANY)

07:24:33.369 (2369490970)|SYSTEM_METHOD_ENTRY|[57]|String.valueOf(Object) 07:24:33.369 (2369498603)|HEAP_ALLOCATE|[57]|Bytes:4 07:24:33.369 (2369510515)|SYSTEM_METHOD_EXIT|[57]|String.valueOf(Object) 07:24:33.369 (2369517681)|HEAP_ALLOCATE|[57]|Bytes:36 07:24:33.369 (2369525908)|SYSTEM_METHOD_ENTRY|[57]|System.debug(ANY) 07:24:33.369 (2369532164)|USER_DEBUG|[57]|DEBUG|@#@# Roll up summary flag 2 ==> true 07:24:33.369 (2369536821)|SYSTEM_METHOD_EXIT|[57]|System.debug(ANY) 07:24:33.369 (2369560049)|STATEMENT_EXECUTE|[59] 07:24:33.369 (2369571207)|SYSTEM_METHOD_ENTRY|[56]|system.ListIterator.hasNext() 07:24:33.369 (2369581442)|HEAP_ALLOCATE|[56]|Bytes:5 07:24:33.369 (2369587814)|SYSTEM_METHOD_EXIT|[56]|system.ListIterator.hasNext() 07:24:33.369 (2369601402)|VARIABLE_ASSIGNMENT|[56]|works|null| 07:24:33.369 (2369614131)|SYSTEM_METHOD_ENTRY|[62]|Set<Id>.size() 07:24:33.369 (2369620439)|SYSTEM_METHOD_EXIT|[62]|Set<Id>.size() 07:24:33.369 (2369627067)|SYSTEM_METHOD_ENTRY|[62]|Set<Id>.size() 07:24:33.369 (2369631733)|SYSTEM_METHOD_EXIT|[62]|Set<Id>.size() 07:24:33.369 (2369637651)|STATEMENT_EXECUTE|[62] 07:24:33.369 (2369641883)|STATEMENT_EXECUTE|[89] 07:24:33.369 (2369659163)|SYSTEM_METHOD_ENTRY|[89]|String.valueOf(Object) 07:24:33.369 (2369665453)|HEAP_ALLOCATE|[89]|Bytes:4 07:24:33.369 (2369676326)|SYSTEM_METHOD_EXIT|[89]|String.valueOf(Object) 07:24:33.369 (2369682704)|HEAP_ALLOCATE|[89]|Bytes:36 07:24:33.369 (2369689718)|SYSTEM_METHOD_ENTRY|[89]|System.debug(ANY) 07:24:33.369 (2369694634)|USER_DEBUG|[89]|DEBUG|@#@# Roll up summary flag 2 ==> true 07:24:33.369 (2369699009)|SYSTEM_METHOD_EXIT|[89]|System.debug(ANY) 07:24:33.369 (2369710354)|STATEMENT_EXECUTE|[91] 07:24:33.369 (2369724566)|CUMULATIVE_LIMIT_USAGE
it also showing like this please check this one

07:42:06.670 (26670197661)|SYSTEM_METHOD_ENTRY|[108]|System.debug(ANY) 07:42:06.670 (26670205636)|USER_DEBUG|[108]|DEBUG|@#@#@ new Functionality Successor Size 1 = 0 Values {} 07:42:06.670 (26670211506)|SYSTEM_METHOD_EXIT|[108]|System.debug(ANY)

07:42:06.671 (26671777636)|SYSTEM_METHOD_ENTRY|[144]|System.debug(ANY) 07:42:06.671 (26671782768)|USER_DEBUG|[144]|DEBUG|@#@#@ new Functionality 12 null 07:42:06.671 (26671787909)|SYSTEM_METHOD_EXIT|[144]|System.debug(ANY)

07:42:06.671 (26671926062)|USER_DEBUG|[145]|DEBUG|@#@#@ new Functionality 123 null null 07:42:06.671 (26671930776)|SYSTEM_METHOD_EXIT|[145]|System.debug(ANY) 07:42:06.671 (26671935800)|STATEMENT_EXECUTE|[147]

07:42:06.672 (26672010639)|SYSTEM_METHOD_ENTRY|[147]|System.debug(ANY) 07:42:06.672 (26672015527)|USER_DEBUG|[147]|DEBUG|@#@#@ new Functionality 1235 null 07:42:06.672 (26672020065)|SYSTEM_METHOD_EXIT|[147]|System.debug(ANY)