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
reddy s 1reddy s 1 

Avoid duplicate record insertion through trigger

Hi everyone, 
below is my trigger with test class,  i am unable to cover the error message.how to cover the error message can some one help me.

trigger dupAccount on Account (before insert) {
    for(Account a:Trigger.new){
        List<Account> acc=[select id,Name from Account where Name=:a.Name];
        if(acc.size() > 0){
           a.Name.addError('cant insert duplicate records');
        }
    }

}

Test Class:
---------------

@isTest
public class dupAccount_Test {
    @isTest 
    static void testme(){
        Account a1=new Account(Name='sam',First_Name__c='test',Last_Name__c='data');
        Account a2=new Account(Name='samm',First_Name__c='tests',Last_Name__c='dataa');
        Test.startTest();
        insert a1;
        insert a2; 
        a2.Name='sam';
        Update a2;
        Test.stopTest();
    }

}


Thanks In Advance,
Reddy.


 
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Reddy,

The test class can be as below. As you wrote the trigger only for insert so inserted the duplicate record.
 
@isTest
public class dupAccount_Test {
    @isTest 
    static void testme(){
        Account a1=new Account(Name='sam');
        Account a2=new Account(Name='sam');
        Test.startTest();
        insert a1;
       
       Database.SaveResult result = Database.insert(a2, false);
        System.assertEquals('cant insert duplicate records',result.getErrors()[0].getMessage());
        Test.stopTest();
    }

}
If this solution helps, Please mark it best answer.

Thanks,
 
AnkaiahAnkaiah (Salesforce Developers) 
Hi,
try with below code. add required fields for account insert as per your org.
@isTest
public class dupAccount_Test {
 
    static testmethod void testme(){
        
        List <Account> acclist = new list<Account>();
        Account a1=new Account(Name='sam');
        acclist.add(a1);
        Account a2=new Account(Name='samm');
        acclist.add(a2);
        insert acclist ;
        Account a3=new Account(Name='samm'); 
        insert a3;

    }

}

If this helps,Please mark it as best answer