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
Allen2Allen2 

Help to complete the test class for the below code

APEX CLASS
trigger AvoidDuplicateUsageEntry on Amendment__c (before insert) 
{
    for (Amendment__c amendment: Trigger.new)
    {
        if (amendment.Override_Warning__c == false)
        {
            try
            {
              Amendment__c[] a = [SELECT a.CreatedById, a.CreatedDate, a.Amendment__c from Amendment__c a where a.Resp__c = :amendment.Resp__c and a.LSD__c = :amendment.LSD__c ORDER BY CreatedDate desc];
              if (a.size() > 0)
              {
                  User u = [SELECT u.Name from User u where id = :a[0].CreatedById];
                  String amendmentStr = String.escapeSingleauotes(a[0].Amendment__c);
                  amendmentStr = amendmentStr.replace('\"', '\\\"');
                  String userStr = String.escapeSingleauotes(u.Name);
                  userStr = userStr.replace('\"', '\\\"');
                  String dateStr = a[0].CreatedDate.format('MM/dd/yyyy hh:mm a');
                  String errorJSON = 'var errorJSON = {timesUsed: ' + a.size() + ', amendment: \"' + amendmentStr + '\", user: \"' + userStr + '\", time: \"' + dateStr + '\"};';  
                  amendment.Resp__c.addError(errorJSON);
              } // endif
            }
            catch (aueryException e)
            {
            }
        } // endif
    } // endfor

}

TEST CLASS
@isTest
public class test_Test {
    
    static testMethod void avoidDuplicateEntryTest() {
        
        Profile p = [select id from profile where name='System Administrator'];
        User u = new User(alias = 'standt', email = 'standarduser@testorg.com', emailencodingkey = 'UTF-8', lastname = 'Testing', languagelocalekey = 'en_US',
                          localesidkey = 'en_US', profileid = p.Id, timezonesidkey = 'America/Los_Angeles',
                          username = 'testclassuser@testorg.com');
        insert u;
        
        System.runAs(u){
            Test.startTest();
            Resp__c resp = new  Resp__c();
            resp.status__c = 'Draft';
            insert resp;
            
            LSD__c ref = new  LSD__c();
            ref.Due_Date__c = system.today();
            insert ref;
            
            list <Amendment__c> as = new list <Amendment__c>();
            Amendment__c amend = new Amendment__c();
            amend.Override_Warning__c = False;
            amend.LSD__c = ref.Id;
            amend.Resp__c = resp.Id; 
            amend.Amendment__c = 'TestText';
            amend.CreatedById = u.Id;
            as.add(amend);
            
            Amendment__c amend1 = new Amendment__c();
            amend1.Override_Warning__c = False;
            amend1.LSD__c = ref.Id;
            amend1.Resp__c = resp.Id; 
            amend1.Amendment__c = 'TestText1';
            amend1.CreatedById = u.Id;
            as.add(amend1);
            insert as;
            
            system.debug('size' + as.size());
            Test.stopTest();
        }      
    }          
}

I am not able to cover the bold & underlined part of my apex class. I am inserting the list in my test class but while debugging I m not getting any value in the list in my test class so unable to cover the rest of the part.

Could anyone can help me in this what is wrong I am doing here.. Please....
Boss CoffeeBoss Coffee
Could you provide clarity as to what the bolded section does?

As for providing coverage for those lines, you could try creating records in a @testSetup before running that test method.
 @testSetup
 static void createRecords() {
    // Set up your user and a couple of Amendment records here
 }

 @isTest
 static testMethod void avoidDuplicateEntryTest() {
   // Insert additional Amendment records here and do any other functionality for testing
 }
Allen2Allen2
Thanks Boss for the help. But I don't think so if we create the setup data and will call that in our test method will work. Creating a setup data is good practice but having a single test method so can insert the data there itself. But here I am creating record for amendment in my test class instead while debugging in apex class where we are retrieving the list of records for amendment, It is coming as null. I m not getting why it is coming as null even the data is present. So only it's not going inside the null check and failing at that point.

Please help me if can do any changes in test class and cover that part.

 
Boss CoffeeBoss Coffee
My apologies, I should have clarified further. For the following query:
try
            {
              Amendment__c[] a = [SELECT a.CreatedById, a.CreatedDate, a.Amendment__c from Amendment__c a where a.Resp__c = :amendment.Resp__c and a.LSD__c = :amendment.LSD__c ORDER BY CreatedDate desc];

...
...
It will fetch from currently existing Amendment records.

In your test class, there are two Amendments inserted, but that fires the Trigger in a before insert context. This means that those records will not be returned when it reaches that query line, so it will not pass that if check.

I believe you can also get coverage for that section in this scenario if you change before insert to after insert so those test records will be returned. Or you could try the @testSetup method where you create existing Amendment records first, then test the insertion of additional Amendment records in a test method.
Allen2Allen2
Hi,

I tried below code... but nothing happened.. still the same result..

@isTest
public class test_Test {
    
    static void setupData(){
        Profile p = [select id from profile where name='System Administrator'];
        User u = new User(alias = 'standt', email = 'standarduser@testorg.com', emailencodingkey = 'UTF-8', lastname = 'Testing', languagelocalekey = 'en_US',
                          localesidkey = 'en_US', profileid = p.Id, timezonesidkey = 'America/Los_Angeles',
                          username = 'testclassuser@testorg.com');
        insert u;
        
        Resp__c resp = new  Resp__c();
        resp.status__c = 'Draft';
        insert resp;
        
        LSD__c ref = new  LSD__c();
        ref.Due_Date__c = system.today();
        insert ref;
        
        //list <Amendment__c> as = new list <Amendment__c>();
        Amendment__c amend = new Amendment__c();
        amend.Override_Warning__c = False;
        amend.LSD__c = ref.Id;
        amend.Resp__c = resp.Id; 
        amend.Amendment__c = 'TestText';
        amend.Source__c = 'Responses';
        amend.CreatedById = u.Id;
        insert amend;
    }
    static testMethod void avoidDuplicateEntryTest() {
        Test.startTest();
        setupData();
        
        Amendment__c amend = [Select Id from Amendment__c where Source__c = 'Responses'];
        amend.Amendment__c = 'Testing';
        update amend;
        Test.stopTest();
    }      
Boss CoffeeBoss Coffee
I believe your Trigger is a before insert? Try changing the following line.
    static testMethod void avoidDuplicateEntryTest() {
        Test.startTest();
        setupData();

        // Instead of update
        // COMMENTED OUT: Amendment__c amend = [Select Id from Amendment__c where Source__c = 'Responses'];
        // COMMENTED OUT: amend.Amendment__c = 'Testing';
        // COMMENTED OUT: update amend;
        
        // Insert another Ammendment
        Amendment__c amend = new Amendment__c();
        amend.Override_Warning__c = False;
        amend.LSD__c = ref.Id;
        amend.Resp__c = resp.Id; 
        amend.Amendment__c = 'TestText';
        amend.Source__c = 'Responses';
        amend.CreatedById = u.Id;
        insert amend;
        
        Test.stopTest();
    }