You need to sign in to do that
Don't have an account?
Test Method for Apex Trigger
Hi,
I have a trigger mentioned below for which I am trying to write a Test Method, but finding difficulties, can anybody help me on the same:
trigger CalculateMaxPoints on Survey__c (before insert, before update)
{
for(Survey__c srv:trigger.new)
{
List<Survey_Question__c> sqrlist =[select Points__c,Type__c from Survey_Question__c where Survey__c =:srv.id ];
Integer maxpoint=0;
for(Survey_Question__c sq:sqrlist)
{
if((sq.Type__c!='Free Text')&&(sq.Points__c!=null))
{
List<String> pointList = sq.Points__c.split('\n');
if((sq.Type__c =='Single Select--Vertical')||(sq.Type__c =='Single Select--Horizontal')||(sq.Type__c =='Free Text'))
{
Integer pointsel=0;
for(Integer p = 0 ;p < pointList.size();p++ )
{
String point = pointList.get(p).trim();
if(pointsel < integer.valueof(point))
try
{
pointsel = integer.valueof(point);
}
catch(Exception e)
{
}
}
maxpoint = maxpoint + pointsel;
}
if(sq.Type__c =='Multi-Select--Vertical')
{
String point;
for(Integer p = 0 ;p < pointList.size();p++ )
{
try
{
maxpoint = maxpoint+ integer.valueof(pointList.get(p).trim());
}
catch(Exception e)
{
}
}
}
}
}
srv.Maximum_points__c = maxpoint;
}
}
Hi,
Try the below class for the test method of your trigger.
@isTest
private class testTriggerinsert_Contact_Activity_11
{
public static testMethod void unitTestinsert_Contact_Activity4Task()
{
Survey__c s1=new Survey__c(name='test');
insert s1;
Survey_Question__c sq=new Survey_Question__c(name='test',Points__c='123',Type__c='Single Select--Vertical',Survey__c=s1.id);
insert sq;
update s1;
sq.Type__c='Multi-Select--Vertical';
update sq;
update s1;
}
}
Did this answer your question? If not, let me know what didn't work, or if so, please mark it solved.
All Answers
Change your trigger code. Dont use query inside for loop.
Hi,
Try the below class for the test method of your trigger.
@isTest
private class testTriggerinsert_Contact_Activity_11
{
public static testMethod void unitTestinsert_Contact_Activity4Task()
{
Survey__c s1=new Survey__c(name='test');
insert s1;
Survey_Question__c sq=new Survey_Question__c(name='test',Points__c='123',Type__c='Single Select--Vertical',Survey__c=s1.id);
insert sq;
update s1;
sq.Type__c='Multi-Select--Vertical';
update sq;
update s1;
}
}
Did this answer your question? If not, let me know what didn't work, or if so, please mark it solved.
Hi,
Thanks a ton. It gave me 90% code coverage. Thanks once again.