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
Jolene Scott-MartinJolene Scott-Martin 

Help - writing a test class for a trigger preventing duplicates

I'm very new to this and managed to write a trigger, preventing a duplicates on a custom object 'Time Estimating' and giving a customised error on screen.  Code is below.

The trigger works perfectly in Sandbox but I can't move the trigger into production as it doesn't include tests.  So I have written a separate apex class to test.  The code is also below.  When I debug I get the following error 'required (...)+ loop did not match anything at input '<EOF>'.  I have googled this to death with no helpful result. When I run tests I get 0% code coverage for the trigger.

Can anyone advise what I have done wrong?  

I'm using the Developer Console (can't install anything else).

Apex Trigger to check for duplicates (called PreventDuplicate)
trigger PreventDuplicate on Time_Estimating__c (before insert, before update){
 
    List<String> uniqueValueList = new List<String>();
    for(Time_Estimating__c a : Trigger.new){
        uniqueValueList.add(a.Unique_Year_Estimate__c);
    }

    List<Time_Estimating__c> acctList = [select id, name, Unique_Year_Estimate__c from Time_Estimating__c where Unique_Year_Estimate__c IN :uniqueValueList];
    Map<String,Time_Estimating__c> uniqueValueMap = new Map<String,Time_Estimating__c>();
    for(Time_Estimating__c a : acctList){
        uniqueValueMap.put(a.Unique_Year_Estimate__c,a);       
    }
 
    for(Time_Estimating__c a : Trigger.new){
        if(uniqueValueMap.containsKey(a.Unique_Year_Estimate__c)){
           
            if(trigger.isInsert || (trigger.isUpdate && a.id<>uniqueValueMap.get(a.Unique_Year_Estimate__c).id)){
                a.addError('A Time Estimate for the year you have specified already exists.  Please click the cancel button and update the existing time estimate.');
            }          
        }
    }
}

Apex class to test trigger (called PreventDuplicateTest)
@isTest

//test for PreventDuplicate trigger on Time Estimating
Public Class PreventDuplicateTest
{
   Static testMethod Void PreventDuplicate()
   {
      Boolean result = false;
      Time_Estimating__c firstAcc = new 
          Time_Estimating__c(Unique_Year_Estimate__c = 'test - 2015',Matter_Name__c = 'test');
      insert firstAcc;
      try{
           Time_Estimating__c secondAcc = new 
               Time_Estimating__c(Unique_Year_Estimate__c = 'test - 2015',Matter_Name__c = 'test');
           insert secondAcc;
       }catch(DmlException ex){ result = true;}
      System.assert(result);
   }
}

Many thanks for your help!
Best Answer chosen by Jolene Scott-Martin
Amit Chaudhary 8Amit Chaudhary 8
Please try below code :-
@isTest
//test for PreventDuplicate trigger on Time Estimating

Public Class PreventDuplicateTest
{
   Static testMethod Void PreventDuplicate()
   {
      Boolean result = false;     
        
           advpm__Matter__c Name = new advpm__Matter__c(Name = 'test');
		insert Name;
       
       Time_Estimating__c firstAcc = new
          Time_Estimating__c(Matter_Name__c = Name.id, Unique_Year_Estimate__c = 'test - 2015', Time_Estimate_Picklist__c = '<0.5 day',Start_Date__c = date.newInstance (2015, 11, 11), End_Date__c = date.newInstance (2015,12,11));
      insert firstAcc;
      try{
           Time_Estimating__c secondAcc = new
           Time_Estimating__c(Matter_Name__c = Name.id , Unique_Year_Estimate__c = 'test - 2015',Time_Estimate_Picklist__c = '<0.5 day', Start_Date__c = date.newInstance (2015, 11, 11),End_Date__c = date.newInstance (2015,12,11));
           insert secondAcc;
       }catch(DmlException ex){ result = true;}
      System.assert(result); 
   }
}


 

All Answers

Jolene Scott-MartinJolene Scott-Martin
BTW when I look at the test reults on PreventDuplicate the error is 'System.StringException: Invalid id: test' and Stack Trace says 'Class.PreventDuplicateTest.PreventDuplicate: line9, column 1'.
Nayana PawarNayana Pawar
Hi Jolene,

Please check below code. Let me know if you got any error.

@IsTest
private class PreventDuplicateTest
{
    static testmethod void PreventDuplicate()
    {
        Time_Estimating__c firstAcc = new Time_Estimating__c(Unique_Year_Estimate__c = '2015',Matter_Name__c = 'testValue');
        insert firstAcc;
        
        Time_Estimating__c secondAcc = new Time_Estimating__c(Unique_Year_Estimate__c = '2015',Matter_Name__c = 'testValueForSecond');
        insert secondAcc;
    }
}
Nayana PawarNayana Pawar

Can you please share data types for :
Unique_Year_Estimate__c & 
Matter_Name__c 
Jolene Scott-MartinJolene Scott-Martin
Hi Nayana, I get the same debug message.  I still get 0% code coverage the error is: System.StringException: Invalid id: testValue and Stack Trace: Class.PreventDuplicateTest.PreventDuplicate: line 6, column 1
 
Amit Chaudhary 8Amit Chaudhary 8
Hi Jolena,

It look like Matter_Name__c is lookup or master detail field. You need to pass Salesforce ID in that field not the value. If that is lookup field then please try below code. I hope that will help you
@isTest

//test for PreventDuplicate trigger on Time Estimating
Public Class PreventDuplicateTest
{
   Static testMethod Void PreventDuplicate()
   {
      Boolean result = false;
      Time_Estimating__c firstAcc = new 
          Time_Estimating__c(Unique_Year_Estimate__c = 'test - 2015');
      insert firstAcc;
      try{
           Time_Estimating__c secondAcc = new 
               Time_Estimating__c(Unique_Year_Estimate__c = 'test - 2015');
           insert secondAcc;
       }catch(DmlException ex){ result = true;}
      System.assert(result);
   }
}
If above code will give error in that case you need to create "Matter_Name__c" field object and need to add like below

Matter_Name__c obj = new Matter_Name__c();
obj.field name ===
insert obj;

      Time_Estimating__c firstAcc = new 
          Time_Estimating__c(Unique_Year_Estimate__c = 'test - 2015',Matter_Name__c = obj.id);

Please check below blog for more information n test classes. I hope that will help u 
http://amitsalesforce.blogspot.in/2015/06/best-practice-for-test-classes-sample.html

Please follow below salesforce Best Practice for Test Classes :-

1. Test class must start with @isTest annotation if class class version is more than 25
2. Test environment support @testVisible , @testSetUp as well
3. Unit test is to test particular piece of code working properly or not .
4. Unit test method takes no argument ,commit no data to database ,send no email ,flagged with testMethod keyword .
5. To deploy to production at-least 75% code coverage is required 
6. System.debug statement are not counted as a part of apex code limit.
7. Test method and test classes are not counted as a part of code limit
9. We should not focus on the  percentage of code coverage ,we should make sure that every use case should covered including positive, negative,bulk and single record .
Single Action -To verify that the the single record produces the correct an expected result .
Bulk action -Any apex record trigger ,class or extension must be invoked for 1-200 records .
Positive behavior : Test every expected behavior occurs through every expected permutation , i,e user filled out every correctly data and not go past the limit .
Negative Testcase :-Not to add future date , Not to specify negative amount.
Restricted User :-Test whether a user with restricted access used in your code .10. Test class should be annotated with @isTest .
11 . @isTest annotation with test method  is equivalent to testMethod keyword .
12. Test method should static and no void return type .
13. Test class and method default access is private ,no matter to add access specifier .
14. classes with @isTest annotation can't be a interface or enum .
15. Test method code can't be invoked by non test request .
16. Stating with salesforce API 28.0 test method can not reside inside non test classes .
17. @Testvisible annotation to make visible private methods inside test classes.
18. Test method can not be used to test web-service call out . Please use call out mock .
19. You can't  send email from test method.
20.User, profile, organization, AsyncApexjob, Corntrigger, RecordType, ApexClass, ApexComponent ,ApexPage we can access without (seeAllData=true) .
21. SeeAllData=true will not work for API 23 version eailer .
22. Accessing static resource test records in test class e,g List<Account> accList=Test.loadData(Account,SobjectType,'ResourceName').
23. Create TestFactory class with @isTest annotation to exclude from organization code size limit .
24. @testSetup to create test records once in a method  and use in every test method in the test class .
25. We can run unit test by using Salesforce Standard UI,Force.com IDE ,Console ,API.
26. Maximum number of test classes run per 24 hour of period is  not grater of 500 or 10 multiplication of test classes of your organization.
27. As apex runs in system mode so the permission and record sharing are not taken into account . So we need to use system.runAs to enforce record sharing .
28. System.runAs will not enforce user permission or field level permission .
29. Every test to runAs count against the total number of DML issued in the process .


Please let us know if this post will help you

Thanks
Amit Chaudhary
Jolene Scott-MartinJolene Scott-Martin
Hi Amit,

That almost worked - I was getting 72% code coverage with your above method, but it was failing because I hadn't included required fields. I have updated with all the required fields, but unfortunately 'Matter_Name__c' is a required field (Master Detail field).

If I understand right, the extra piece of code you suggestted will insert a record into the master record, which I can then reference in 'Matter_Name__c' . So I have inserted that extra code and it looks like this:
@isTest
//test for PreventDuplicate trigger on Time Estimating

Public Class PreventDuplicateTest
{
   Static testMethod Void PreventDuplicate()
   {
      Boolean result = false;     
        
           advpm__Matter__c Name = new advpm__Matter__c(Name = 'test');
		insert Name;
       
       Time_Estimating__c firstAcc = new
          Time_Estimating__c(Matter_Name__c = '01Ib00000001Xfc', Unique_Year_Estimate__c = 'test - 2015', Time_Estimate_Picklist__c = '<0.5 day',Start_Date__c = date.newInstance (2015, 11, 11), End_Date__c = date.newInstance (2015,12,11));
      insert firstAcc;
      try{
           Time_Estimating__c secondAcc = new
           Time_Estimating__c(Matter_Name__c = '01Ib00000001Xfc', Unique_Year_Estimate__c = 'test - 2015',Time_Estimate_Picklist__c = '<0.5 day', Start_Date__c = date.newInstance (2015, 11, 11),End_Date__c = date.newInstance (2015,12,11));
           insert secondAcc;
       }catch(DmlException ex){ result = true;}
      System.assert(result); 
   }
}

The error now says: System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, Matter Name: id value of incorrect type: 01Ib00000001XfcEAE: [Matter_Name__c].  I am also getting 0% code coverage again with this updated code.

So I'm guessing I'm using the wrong ID or have done something incorrect earlier in the code to cause this.  There are the IDs of the various objects and fields;

The master object is called 'advpm__Matter__c'.  (id 01Ib00000001Xfc)
The field I'm looking up is 'Name' (id 01Ib00000001Xfc)

The detail object is called Time_Estimating__c. (id 01IK0000000AbjH)
The Mater Detail field is called Matter_Name__c (id 00NK0000001hrRk)

Thank you for your help and patience! 

Jolene
Amit Chaudhary 8Amit Chaudhary 8
Please try below code :-
@isTest
//test for PreventDuplicate trigger on Time Estimating

Public Class PreventDuplicateTest
{
   Static testMethod Void PreventDuplicate()
   {
      Boolean result = false;     
        
           advpm__Matter__c Name = new advpm__Matter__c(Name = 'test');
		insert Name;
       
       Time_Estimating__c firstAcc = new
          Time_Estimating__c(Matter_Name__c = Name.id, Unique_Year_Estimate__c = 'test - 2015', Time_Estimate_Picklist__c = '<0.5 day',Start_Date__c = date.newInstance (2015, 11, 11), End_Date__c = date.newInstance (2015,12,11));
      insert firstAcc;
      try{
           Time_Estimating__c secondAcc = new
           Time_Estimating__c(Matter_Name__c = Name.id , Unique_Year_Estimate__c = 'test - 2015',Time_Estimate_Picklist__c = '<0.5 day', Start_Date__c = date.newInstance (2015, 11, 11),End_Date__c = date.newInstance (2015,12,11));
           insert secondAcc;
       }catch(DmlException ex){ result = true;}
      System.assert(result); 
   }
}


 
This was selected as the best answer
Jolene Scott-MartinJolene Scott-Martin
Thank you Amit, that worked.  100% code coverage. :)
Madhukar Reddy VuradiMadhukar Reddy Vuradi
Please check below code. 

@IsTest
private class PreventDuplicateTest
{
    static testmethod void PreventDuplicate()
    {
        Time_Estimating__c firstAcc = new Time_Estimating__c(Unique_Year_Estimate__c = '2015',Matter_Name__c = 'testValue');
        insert firstAcc;
        
        firstAcc = new Time_Estimating__c(Unique_Year_Estimate__c = '2015',Matter_Name__c = 'testValue');
        insert firstAcc;
    }
}