You need to sign in to do that
Don't have an account?
Hiral Shah 16
Hii I am trying to write test class for the following apex trigger code.Please help me to cover 75% of code coverage
In this Leave and the Resource are custom object. Leave has lookup relationship with Resource . Leave has the custom field Leaves__c. For the one Resource total Leaves__c will be calculated in Total_Used_Paid_Leaves__c (custom field) in Resource__c object.
my apex trigger
trigger LeaveTrigger on Leave__c (after insert,after update) {
if(trigger.isInsert || trigger.isUpdate){
HRLeaveController.getTotalLeaves(Trigger.New);
}
}
Apex class code
public class HRLeaveController{
public static void getTotalLeaves(List<Leave__c> newLeaves){
Set<ID> resId = new Set<ID>();
List<Resource__c> listRes = new List<Resource__c>();
List<Resource__c> updateRes = new List<Resource__c>();
for(Leave__c lev : newLeaves){
resId.add(lev.Resource__c);
}
if(resId.size() > 0){
listRes = [select Id,Total_Used_Paid_Leaves__c ,(select Id,Leaves__c from Leaves__r) from Resource__c where Id IN : resId];
}
for(Resource__c resrc : listRes){
Decimal val = 0;
for(Leave__c levs : resrc.Leaves__r){
val += levs.Leaves__c;
System.debug('**val**'+val);
}
resrc.Total_Used_Paid_Leaves__c = val;
updateRes.add(resrc);
}
if(!updateRes.isEmpty()){
update updateRes;
}
}
}
my apex trigger
trigger LeaveTrigger on Leave__c (after insert,after update) {
if(trigger.isInsert || trigger.isUpdate){
HRLeaveController.getTotalLeaves(Trigger.New);
}
}
Apex class code
public class HRLeaveController{
public static void getTotalLeaves(List<Leave__c> newLeaves){
Set<ID> resId = new Set<ID>();
List<Resource__c> listRes = new List<Resource__c>();
List<Resource__c> updateRes = new List<Resource__c>();
for(Leave__c lev : newLeaves){
resId.add(lev.Resource__c);
}
if(resId.size() > 0){
listRes = [select Id,Total_Used_Paid_Leaves__c ,(select Id,Leaves__c from Leaves__r) from Resource__c where Id IN : resId];
}
for(Resource__c resrc : listRes){
Decimal val = 0;
for(Leave__c levs : resrc.Leaves__r){
val += levs.Leaves__c;
System.debug('**val**'+val);
}
resrc.Total_Used_Paid_Leaves__c = val;
updateRes.add(resrc);
}
if(!updateRes.isEmpty()){
update updateRes;
}
}
}
Create a testmethod and insert Resource__c and Leave__c object records by giving all the required fields.Kindly modify below code as per your requirements Hope this helps you
If this helps kindly mark it as solved so that it may help others in future.
Thanks and Regards
All Answers
Create a testmethod and insert Resource__c and Leave__c object records by giving all the required fields.Kindly modify below code as per your requirements Hope this helps you
If this helps kindly mark it as solved so that it may help others in future.
Thanks and Regards