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
ganeshjujjuruganeshjujjuru 

how can i cover addError() message of trigger in test clas..?

can any body help me how can i cover addError() message of trigger in test clas..?

amarcuteamarcute

Hi,

 

You need to create test case with test data covering the error condition.

 

Example:

insert value for NumberOfStudents__c which is greater than MaxSize__c to meet the error condition.

 

Trigger

trigger insertStudent on Student__c (before insert ) {
Map<id,class__C> claMap=new Map<id,class__C>([select NumberOfStudents__c,MaxSize__c from class__c]);
for(Student__c s:Trigger.new){
class__c cls=claMap.get(s.class__c);
if(cls.NumberOfStudents__c >=cls.MaxSize__c){
s.addError('Can not add');
}
}
}

 

Test

@isTest
private class test_triggerOnMyCount{
static testmethod void triggerTest(){
class__C cls=new class__C();
cls.Name__c = 'Apex' ;
cls.MaxSize__c=1;
insert cls;
System.assertEquals(null,cls.NumberOfStudents__c );
Student__C std = new Student__C();
std.Last_Name__c='XYZ';
std.class__C=cls.id;
insert std;
cls=[select MyCount__c from class__C where id=: cls.id];
System.assertEquals(1,cls.NumberOfStudents__c );

Student__C std2 = new Student__C();
std2.Last_Name__c='XYZ2';
std2.class__C=cls.id;
insert std2;
cls=[select MyCount__c from class__C where id=: cls.id];
System.assertEquals(1,cls.NumberOfStudents__c );

amarcuteamarcute

Posting the complete test class code again...

 

Test

@isTest
private class test_triggerOnMyCount{
static testmethod void triggerTest(){
class__C cls=new class__C();
cls.Name__c = 'Apex' ;
cls.MaxSize__c=1;
insert cls;
System.assertEquals(null,cls.NumberOfStudents__c );
Student__C std = new Student__C();
std.Last_Name__c='XYZ';
std.class__C=cls.id;
insert std;
cls=[select MyCount__c from class__C where id=: cls.id];
System.assertEquals(1,cls.NumberOfStudents__c );




Student__C newstd = new Student__C();
newstd .Last_Name__c='Tejpal';
newstd .class__C=cls.id;

insert newstd ;

 

Student__C std2 = new Student__C();
std2.Last_Name__c='XYZ2';
std2.class__C=cls.id;
insert std2;
cls=[select MyCount__c from class__C where id=: cls.id];
System.assertEquals(1,cls.NumberOfStudents__c );


}
catch (Exception e){

System.assert(e.getMessage().contains('Can not add'));


}


}

}

Suraj Tripathi 47Suraj Tripathi 47
Hello Ganesh,

Whenever you perform an insert or update DML Operation, please use Database.insert(List<SObject> updateList, false) instead of direct insert as well as Database.update.
make sure the SObject list has those records which will raise an error.

If you find your Solution then Mark this as Best Answer

Thank you!

Regards,
Suraj Tripathi