Unit Testing for Triggers

Sample Trigger:

trigger DuplicateMemberCheck on Member__c (before insert)
{
for(Member__c memb:trigger.new)
{
List<Member__c> mem = new List<Member__c>();

String email = memb.E_Mail_Id__c;

String sql = 'SELECT E_Mail_Id__c FROM Member__c';
mem = Database.Query(sql);

for(Member__c tempMember:mem)
{
if(tempMember.E_Mail_Id__c == email)
{
memb.E_Mail_Id__c.addError('Duplicate Record');
}
}
}
}

Sample Test Class for Sample Trigger:

@isTest

public class TestDuplicateMemberCheckClass
{
    static testMethod void test()
    {
        Date birthday = Date.valueOf('2000-12-20');

        Member__c mem = new Member__c(Name = 'Test', E_Mail_Id__c = 'magulan.d@igatepatni.com', Mobile_Number__c = '99966663322', Birthday__c = birthday);
       
        Member__c mem1 = new Member__c(Name = 'Test', E_Mail_Id__c = 'magulan@igatepatni.com', Mobile_Number__c = '99966663322', Birthday__c = birthday);

        try
        {
            insert mem;
            insert mem1;
        }
        catch(DMLException e)
        {
            System.assert(e.getMessage().contains('Duplicate Record'));
        }
    }   
}

Output:

No comments:

Post a Comment