You need to sign in to do that
Don't have an account?

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..?
You need to sign in to do that
Don't have an account?
can any body help me how can i cover addError() message of trigger in test clas..?
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 );
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'));
}
}
}
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