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
Lakshmi SLakshmi S 

adderror test class for Trigger

HI Dev's

I am trying to 100% code coverage, but this test class covers only 75%. How can we achieve that?
Please guide me any one.

Trigger
----------
trigger AccountDuplicateTrigger on Account (before insert,before update) {
    
    for(Account acc : Trigger.New){
        for(Account ac : [Select id,name from Account]){
            if(acc.name == ac.name && acc.name != Trigger.oldmap.get(acc.Id).name){
                acc.Name.addError('You cannot create duplicate Account');
            }
        }
    }
    
}

Test Class
---------------
@isTest
public class TestAccountDuplicateTrigger {
    static testMethod void test(){
        boolean result = false;
        Account a =new Account(name='Demo');
        insert a;
        Account aa = new Account(name='Demo');
        
        try{
            Database.insert(aa);
        }
        catch(DMLException de){
            
            result=true;
            System.assert(result);
            System.assert(de.getMessage().contains('You cannot create duplicate Account'));
        }
    }

}



Thanks in Advance
Lakshmi
devedeve
Hi Lakshmi S,

Trigger you have written is work only for before update and not for before insert because oldmap is only available in update and delete triggers.You can change OR(||) in place of AND(&&) in' if' condition of trigger so your test class will work perfectly with 100% coverage.

Thanks
Lakshmi SLakshmi S
Hi Jyoti Agrawal,

Thanks for your reply.
I have seperated before insert and update operations.
Now its covered 100% .

Regards
Lakshmi.