+ Start a Discussion
Force.platformForce.platform 

Test class for trigger that prevent duplicated record

i want test class for trigger that prevent duplicate record.
Trigger PreventDuplicateSR on BMCServiceDesk__Incident__c(Before insert)
{
  List<BMCServiceDesk__Incident__c>  allIncident = new  List<BMCServiceDesk__Incident__c>();
  allIncident = [SELECT Id, Name,BMCServiceDesk__FKClient__c,BMCServiceDesk__Service_Request_Title__c from BMCServiceDesk__Incident__c
                               Where BMCServiceDesk__Service_Request_Title__c = 'Tablet'
                                     OR BMCServiceDesk__Service_Request_Title__c = 'Tablet w/ Bluetooth Scanner'
                                     OR BMCServiceDesk__Service_Request_Title__c = 'FIT Team Device (Handheld)'
                                     OR BMCServiceDesk__Service_Request_Title__c = 'Laptop Computer '];
 
 
  for(BMCServiceDesk__Incident__c inc: trigger.new)
  {
      for(BMCServiceDesk__Incident__c oldInc: allIncident )
      {
          if(inc.BMCServiceDesk__FKClient__c == oldInc.BMCServiceDesk__FKClient__c
             && inc.BMCServiceDesk__state__c == True &&
             inc.BMCServiceDesk__Service_Request_Title__c == oldInc.BMCServiceDesk__Service_Request_Title__c)
              {
              inc.addError('You have already requested for this service');
              }
      }
  }     
 
}
Steven NsubugaSteven Nsubuga
You may need to make some modifications in case I used the wrong data for the BMCServiceDesk__FKClient__c  field in the test.
@isTest
private class PreventDuplicateSRTest{

	@isTest static void testTrigger() {
	
		List<String>  titles = new  List<String>{'Tablet', 'Tablet w/ Bluetooth Scanner', 'FIT Team Device (Handheld)', 'Laptop Computer '};
		List<BMCServiceDesk__Incident__c>  allIncidents = new  List<BMCServiceDesk__Incident__c>();
		for(Integer i = 1; i < 5;i++  ) {
			BMCServiceDesk__Incident__c incident = new BMCServiceDesk__Incident__c();
			incident.BMCServiceDesk__state__c = true;
			incident.Service_Request_Title__c = titles[i-1];
			incident.BMCServiceDesk__FKClient__c = 'Client';
			allIncidents.add(incident);
        }
		insert allIncidents;
		
		try {
			BMCServiceDesk__Incident__c newIncident = new BMCServiceDesk__Incident__c();
			newIncident.BMCServiceDesk__state__c = true;
			newIncident.Service_Request_Title__c = 'Tablet';
			newIncident.BMCServiceDesk__FKClient__c = 'Client';
			insert newIncident;
		} 
		catch (Exception e) {
			System.assert(e.getMessage().contains('You have already requested for this service'));
		}		
	}

}