+ Start a Discussion
sp13sp13 

test class for trigger to prevent duplication of records

hello :) i searched this code to prevent duplication of records in an object.

trigger PreventFuelDuplication on Fuel__c (before insert, before update) {
    Map<String, Fuel__c> leadMap = new Map<String, Fuel__c>();
    for (Fuel__c lead : System.Trigger.new) {
           
        if ((lead.Name != null) && (System.Trigger.isInsert || (lead.Name != System.Trigger.oldMap.get(lead.Id).Name))) {
            if (leadMap.containsKey(lead.Name)) {
                lead.Name.addError('This Fuel already exists.');
            } else {
                leadMap.put(lead.Name, lead);
            }
       }
    }
   
    for (Fuel__c lead : [SELECT Name FROM Fuel__c WHERE Name IN :leadMap.KeySet()]) {
        Fuel__c newLead = leadMap.get(lead.Name);
        newLead.Name.addError('This Fuel already exists.');
    }
}

i need to create a test class for this and i have no idea how. can anyone help me please?

 

suresh143suresh143
where i have raise problem in boards in new version
Satyendra RawatSatyendra Rawat
Hi

@isTest
private class TestPreventFuelDuplication
{
   static testMethod void PreventFuelDuplicationUnitTest()
    {
        Fuel__c newFuel = new Fuel__c();
        newFuel.Name='new Fuel';
       // write here code if more field value are required then set the value 
       insert newFuel;
       newFuel.name = 'new Fuel';
      database.SaveResult result = Database.update(newFuel,false);
     System.assertEquals(result.getErrors()[0].getMessage(),'This Fuel already exists.');
     }
}
sp13sp13

thank you @Satya_007 :)

however it shows this error:

Pass/Fail: Fail
Error Message: System.ListException: List index out of bounds: 0
Stack Trace: Class.PreventFuelDuplication_Test.PreventFuelDuplicationUnitTest: line 12, column 1

i tried removing [0] but it still shows error. is there something wrong?

thanks for the help and merry christmas :)