+ Start a Discussion
raz rraz r 

Test class covers only 66% . Please help to cover 100%

Trigger:
trigger RestrictContactByName on Contact (before insert, before update) {
    
    //check contacts prior to insert or update for invalid data
    For (Contact c : Trigger.New) {
        if(c.LastName == 'INVALIDNAME') {    //invalidname is invalid
            c.AddError('The Last Name "'+c.LastName+'" is not allowed for DML');
        }

    }
}

Test class:

@istest
public class TestRestrictContactByName {
    
    public static testmethod void testcontact1(){
        list<contact> cont=new list<contact>();
        contact con =new contact(lastname='testttt');
        cont.add(con);
        try{
        insert con;
        }
        catch(System.DmlException e){
             
        system.assert(e.getmessage().contains('The lastname testttt is not allow for DML'));
        }
    }
    
    public static testmethod void testcontact2(){
        list<contact> conn=new list<contact>();
        contact con =new contact(lastname='testtttt');
        conn.add(con);
        try{
        insert conn;
        }
        catch(System.DmlException e){
             
        //system.assert(e.getmessage().contains('The lastname testtttt is not allow for DML'));
        }
        
        conn.get(0).lastname='Invaliddata';
    
    try{
        update conn;
    }
    catch(System.DmlException e){
        system.assert(e.getmessage().contains('The lastname Invaliddata is not allow for DML'));
        
    }
}
}

 
Best Answer chosen by raz r
Subodh shuklaSubodh shukla
plzz try this code
@ isTest
public class TestRestrictContactByName {

public static testmethod void RestrictContactByNameTest(){


Contact cnt2 = new Contact(FirstName='Test1',LastName='INVALIDNAME');
database.SaveResult s =database.insert(cnt2, false);
 
	system.assert(!s.issuccess());
}


}

 

All Answers

raz rraz r
Thanks for your help. While iam run this test class iam getting below error. Anyway it covers 100%.
System.DmlException: Insert failed. First exception on row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, The Last Name &quot;INVALIDNAME&quot; is not allowed for DML: []
Subodh shuklaSubodh shukla
plzz try this code
@ isTest
public class TestRestrictContactByName {

public static testmethod void RestrictContactByNameTest(){


Contact cnt2 = new Contact(FirstName='Test1',LastName='INVALIDNAME');
database.SaveResult s =database.insert(cnt2, false);
 
	system.assert(!s.issuccess());
}


}

 
This was selected as the best answer
raz rraz r
Yes , It works! Thanks for your help.