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
Andrew Hoban 6Andrew Hoban 6 

Creating a test class for Class and Trigger

Hi all,

I have created a class and a trigger that calls the class, but now I am struggling to create test classes for these. I was wondering if anyone could help with creating  a test class for these.

Thanks

Class
public class AutomatedApprovalRequest {

    public static void submitApproval(Id id){
    
    //creates a new instance of Approval Process
    Approval.Processsubmitrequest procReq;
    
    //creates a ProcessSubmitRequest object to submit the record for Approval
    procReq = new Approval.Processsubmitrequest();
    
    procReq.setComments('Submitting site set for approval');
    
    //set the record id being submitted to approval
    procReq.setObjectID(id);
    
    //submit the record for approval
    Approval.Processresult result = Approval.process(procReq);
    
    }
    
  }
Trigger
trigger ApproveProcessAutomation on IT_Purchase_Orders__c (after insert, after update) {

  IT_Purchase_Orders__c PurchaseOrders = Trigger.new[0];
        if(PurchaseOrders.Total_Formula__c >= 500.00){
        
        //call approval method
        AutomatedApprovalRequest.submitApproval(PurchaseOrders.id);
               
       
       }
       

}


 
Best Answer chosen by Andrew Hoban 6
Amit Chaudhary 8Amit Chaudhary 8
Please try below test class.
@isTest(SeeAllData=true)
public class AutomatedApprovalRequest_Test{

public testmethod static void runTest(){  
    
        IT_Purchase_Orders__c PO = new IT_Purchase_Orders__c(
            Product__c = 'Test Name',
            Quantity__c = 4,
            Status__c = 'Pending',
            Price__c = 600.00,
            Ordered_By__c = 'Andrew Hoban' );
        try
		{
			insert PO;
        }
		catch(Exception ee)
		{
			
		}	
    }
}

NOte:- according to approval process Total_Formula__c should be > 500. Please try to add values > 500 accordong to formula field.
Please share screen shot of formual field

Please let us know if this will help u
 

All Answers

Amit Chaudhary 8Amit Chaudhary 8
Hi ,
Please check below post. How to write test classess in salesforce
http://amitsalesforce.blogspot.in/2015/06/best-practice-for-test-classes-sample.html

Please try below code i hope that will help u
@isTest 
public class ApproveProcessAutomationTest 
{
	static testMethod void testMethod1() 
	{
		IT_Purchase_Orders__c obj = new IT_Purchase_Orders__c();
		//obj.Total_Formula__c =501:
		// Please add all required field data here
		insert obj;
		
	}
}




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
RAM AnisettiRAM Anisetti
Hi Andrew Hoban 6,

Try this one...

@isTest(SeeAlllData=true)

public class AutomatedApprovalRequest_Test{

public testmethod static void runTest(){

IT_Purchase_Orders__c po=new IT_Purchase_Orders__c();
po.Total_Formula__c=500.00;
// similarly you can mention required data
insert po;

AutomatedApprovalRequest.submitApproval(po.id);
}


}
Andrew Hoban 6Andrew Hoban 6
Hi, thanks for the reply.

I am getting the error message:

Error Message System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, ApproveProcessAutomation: execution of AfterInsert

caused by: System.DmlException: Process failed. First exception on row 0; first error: NO_APPLICABLE_PROCESS, No applicable approval process was found.: []

Class.AutomatedApprovalRequest.submitApproval: line 17, column 1
Trigger.ApproveProcessAutomation: line 7, column 1: []


Stack Trace Class.ApproveProcessAutomationTest.testMethod1: line 14, column 1
Andrew Hoban 6Andrew Hoban 6
Approval Process

I am getting this error message when im trying to save the record with the trigger

Validation Errors While Saving Record(s) There were custom validation error(s) encountered while saving the affected record(s). The first validation error encountered was "Apex trigger ApproveProcessAutomation caused an unexpected exception, contact your administrator: ApproveProcessAutomation: execution of BeforeUpdate caused by: System.DmlException: Process failed. First exception on row 0; first error: ALREADY_IN_PROCESS, Cannot submit object already in process.: []: Class.AutomatedApprovalRequest.submitApproval: line 17, column 1".

Click here to return to the previous page.


Test class:
@isTest(SeeAllData=true)
public class AutomatedApprovalRequest_Test{

public testmethod static void runTest(){  
    
        IT_Purchase_Orders__c PO = new IT_Purchase_Orders__c(
            Product__c = 'Test Name',
            Quantity__c = 4,
            Status__c = 'Pending',
            Price__c = 600.00,
            Ordered_By__c = 'Andrew Hoban' );
        insert PO;
        
        AutomatedApprovalRequest.submitApproval(po.id);
           
    }
}

 
Amit Chaudhary 8Amit Chaudhary 8
Please try below test class.
@isTest(SeeAllData=true)
public class AutomatedApprovalRequest_Test{

public testmethod static void runTest(){  
    
        IT_Purchase_Orders__c PO = new IT_Purchase_Orders__c(
            Product__c = 'Test Name',
            Quantity__c = 4,
            Status__c = 'Pending',
            Price__c = 600.00,
            Ordered_By__c = 'Andrew Hoban' );
        try
		{
			insert PO;
        }
		catch(Exception ee)
		{
			
		}	
    }
}

NOte:- according to approval process Total_Formula__c should be > 500. Please try to add values > 500 accordong to formula field.
Please share screen shot of formual field

Please let us know if this will help u
 
This was selected as the best answer
Andrew Hoban 6Andrew Hoban 6
Thank you, this test class has now passed. When I am attempting to save a record in my object, I am now getting this message. Is there something I need to ammend.
Thanks for the help
User-added image
Andrew Hoban 6Andrew Hoban 6
What would be the workaround? The record will not save due to this validation error.
RAM AnisettiRAM Anisetti
Hi,
The reason you're getting this error message is because you cannot submit a record which is already in the approval process. And the reason I think it is getting submitted again is because this trigger is getting called more than once which might be caused by a workflow field update etc.
So to avoid this error message you can use a static variable, set it to false after the records is submitted. Check for this static varaible in the if () condition and that should do the trick.


public class SampleStoprecursive
{
public static boolean isTwice=false;
}


public class AutomatedApprovalRequest {

    public static void submitApproval(Id id){
    
    //creates a new instance of Approval Process
    Approval.Processsubmitrequest procReq;
    
    //creates a ProcessSubmitRequest object to submit the record for Approval
    procReq = new Approval.Processsubmitrequest();
    
    procReq.setComments('Submitting site set for approval');
    
    //set the record id being submitted to approval
    procReq.setObjectID(id);
    
    //submit the record for approval
    Approval.Processresult result = Approval.process(procReq);


  
    SampleStoprecursive.isTwice = true;

    
    }
    
  }





 
Amit Chaudhary 8Amit Chaudhary 8
This issue is coming due to some field update or some other trigger. Due to that your same trigger is again firing again. In that case you need to check your record is in approval process or not.

There are two way to check this . Please check below post i hope that will help u
http://amitsalesforce.blogspot.in/2015/03/how-to-stop-recursive-trigger-in.html

Solution 1:- Add Check in trigger:-

Step1 :- Please create below class
public class ApproveProcessAutomationHandler
{
     public static Boolean isFirstTime = true;
}

Step 2:- Modify your trigger code.
 
trigger ApproveProcessAutomation on IT_Purchase_Orders__c (after insert, after update) 
{

	if(ApproveProcessAutomationHandler.isFirstTime)
	{
		ApproveProcessAutomationHandler.isFirstTime =  false;
		IT_Purchase_Orders__c PurchaseOrders = Trigger.new[0];
        if(PurchaseOrders.Total_Formula__c >= 500.00)
		{
			//call approval method
			AutomatedApprovalRequest.submitApproval(PurchaseOrders.id);
		}
	}	
}


Solution 2:- Please create on check box field on same object underApprocal to check record is under approval or not
Step 1:- Create one field underApproval__c on same object
Step 2:- Add on field update on approval to update the field as true once record submitted on approval process
Step 3:- Modify your trigger like below 
trigger ApproveProcessAutomation on IT_Purchase_Orders__c (after insert, after update) 
{

		IT_Purchase_Orders__c PurchaseOrders = Trigger.new[0];
        if(PurchaseOrders.Total_Formula__c >= 500.00 && underApproval__c == false)
		{
			//call approval method
			AutomatedApprovalRequest.submitApproval(PurchaseOrders.id);
		}
}

Please let us know if this will help u
 
Andrew Hoban 6Andrew Hoban 6
Hi,

Would it be due to the field being a formula?

I have inserted what you advidsed but im still getting this error message.

Class1
public class SampleStoprecursive
{
public static boolean isTwice=false;
}

Class2
public class AutomatedApprovalRequest {


    public static void submitApproval(Id id){
    
    
    
    //creates a new instance of Approval Process
    Approval.Processsubmitrequest procReq;
    
    //creates a ProcessSubmitRequest object to submit the record for Approval
    procReq = new Approval.Processsubmitrequest();
    
    procReq.setComments('Submitting site set for approval');
    
    //set the record id being submitted to approval
    procReq.setObjectID(id);
    
    //submit the record for approval
    Approval.Processresult result = Approval.process(procReq);

     SampleStoprecursive.isTwice = true;
 
    
    }
    
  }

Trigger
trigger ApproveProcessAutomation on IT_Purchase_Orders__c (after insert, after update) {

  IT_Purchase_Orders__c PurchaseOrders = Trigger.new[0];
        if(PurchaseOrders.Total_Formula__c >= 500.00){
        
        //call approval method
        AutomatedApprovalRequest.submitApproval(PurchaseOrders.id);

        SampleStoprecursive.isTwice = true;
        
               
       
       }
       

}



 
Andrew Hoban 6Andrew Hoban 6
Thank you to all! This is now working and ive learnt quite a bit

Thanks