Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
ShowAll Questionssorted byDate Posted
Sunay - KVP Bus Solns

# 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;

}
}

Navatar_DbSup

Hi,

Try the below class for the test method of your trigger.

@isTest
private class testTriggerinsert_Contact_Activity_11
{
{
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.

Nilesh Mane

Change your trigger code. Dont use query inside for loop.

Navatar_DbSup

Hi,

Try the below class for the test method of your trigger.

@isTest
private class testTriggerinsert_Contact_Activity_11
{
{
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.

This was selected as the best answer
Sunay - KVP Bus Solns

Hi,

Thanks a ton. It gave me 90% code coverage. Thanks once again.