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
Craig PhoenixCraig Phoenix 

Code Coverage For Statements Related To Field Generated By Custom Setting List

I have a trigger that is effectively checking a custom list to match the Close Date with the Start/End dates for weeks so a custom field is populated with the text of the Start and End dates.

Trigger:
trigger CloseWeekUpdate on Opportunity (before insert, before update) {
    Try{
        for(Opportunity opp : trigger.new){
            if(opp.CloseDate != NULL){
                system.debug('opp.CloseDate = ' + opp.CloseDate);
                for(CloseDateWeek__c rec : CloseDateWeek__c.getAll().values()){
                    if (opp.CloseDate >= rec.WeekStartDate__c && opp.CloseDate <= rec.WeekEndDate__c){
                        system.debug('rec.WeekStartDate__c = ' + rec.WeekStartDate__c);
                        system.debug('rec.WeeEndDate__c = ' + rec.WeekEndDate__c);
                        opp.Close_Week__c = rec.WeekStartDate__c.format() + ' - ' + rec.WeekEndDate__c.format();
                        system.debug('rec.Close_Week__c = ' + opp.Close_Week__c);
                        break;
                    }
                }
            }
        }
    }
    Catch(Exception Ex){
        system.debug('Exception Details = ' + Ex);
    }


I have built a test class to insert a test Opportunity and I am getting to 50% but unable to get higher, how do I get the class to test the following lines from the Trigger?

Lines that are not testing:

- for(CloseDateWeek__c rec : CloseDateWeek__c.getAll().values()){
- if (opp.CloseDate >= rec.WeekStartDate__c && opp.CloseDate <= rec.WeekEndDate__c){
- opp.Close_Week__c = rec.WeekStartDate__c.format() + ' - ' + rec.WeekEndDate__c.format();

Here is the Test class I have:
@isTest
    public class TestCloseWeekUpdate {
        static testMethod void testCloseWeek(){
            Opportunity to = new Opportunity();
            to.Name = 'Test Name';
            to.CloseDate = Date.newInstance(2020,06,06);
            to.StageName = 'Closed Won';
            to.Start_Date__c = Date.newInstance(2020,06,01);
            to.Type = 'New Business';
            to.Market__c = 'Large';
            to.Premium__c = TRUE;
            to.Startup_Needed__c = 'Yes';
            insert to;
            test.startTest();
            try{
                to.Close_Week__c = '5/31/2020 - 6/6/2020';
            }
            Catch (Exception ee){}
            test.stopTest();
        }
    }


Any help with getting that last 3 lines covered is greatly appreciated! 
Best Answer chosen by Craig Phoenix
Maharajan CMaharajan C
Hi Craig,

First you have to create the test data for custom setting then you have to insert the opportunity:

Please refer the below code:
 
@isTest
    public class TestCloseWeekUpdate {

        static testMethod void testCloseWeek(){
		
			CloseDateWeek__c cdw1 = new CloseDateWeek__c();
			cdw1.WeekStartDate = Date.newInstance(2020,05,31);
			cdw1.WeekEndDate = Date.newInstance(2020,06,06);
			insert cdw1;
			
            Opportunity to = new Opportunity();
            to.Name = 'Test Name';
            to.CloseDate = Date.newInstance(2020,06,06);
            to.StageName = 'Closed Won';
            to.Start_Date__c = Date.newInstance(2020,06,01);
            to.Type = 'New Business';
            to.Market__c = 'Large';
            to.Premium__c = TRUE;
            to.Startup_Needed__c = 'Yes';
            // add if any other fields are required to insert the Opportunity
            test.startTest();
			insert to;
			system.assertEquals('5/31/2020 - 6/6/2020',to.Close_Week__c);
            test.stopTest();
        }
    }

Thanks,
Maharajan.C

All Answers

Andrew GAndrew G
Custom Settings are considered data.  So you will need to create them for the Test class. 

In your test class add something like:
CloseDateWeek__c cdw1 = new CloseDateWeek__c();
cdw1.WeekStartDate = Date.newInstance(2020,05,31);
cdw1.WeekEndDate = Date.newInstance(2020,06,06);
insert cdw1;

Else you could use (SeeAllData=true).  Not my preferred practice unless absolutely necessary.

Regards
Andrew
Maharajan CMaharajan C
Hi Craig,

First you have to create the test data for custom setting then you have to insert the opportunity:

Please refer the below code:
 
@isTest
    public class TestCloseWeekUpdate {

        static testMethod void testCloseWeek(){
		
			CloseDateWeek__c cdw1 = new CloseDateWeek__c();
			cdw1.WeekStartDate = Date.newInstance(2020,05,31);
			cdw1.WeekEndDate = Date.newInstance(2020,06,06);
			insert cdw1;
			
            Opportunity to = new Opportunity();
            to.Name = 'Test Name';
            to.CloseDate = Date.newInstance(2020,06,06);
            to.StageName = 'Closed Won';
            to.Start_Date__c = Date.newInstance(2020,06,01);
            to.Type = 'New Business';
            to.Market__c = 'Large';
            to.Premium__c = TRUE;
            to.Startup_Needed__c = 'Yes';
            // add if any other fields are required to insert the Opportunity
            test.startTest();
			insert to;
			system.assertEquals('5/31/2020 - 6/6/2020',to.Close_Week__c);
            test.stopTest();
        }
    }

Thanks,
Maharajan.C
This was selected as the best answer
Craig PhoenixCraig Phoenix
Thanks for the info, still not getting coverage though but I am getting a new error:

System.AssertException: Assertion Failed: Expected: 5/31/2020 - 6/6/2020, Actual: null

Is there something I am missing to get it to run the Trigger to make the Close_Week__c have the expected value of 5/31/2020 - 6/6/2020 ?
Maharajan CMaharajan C
As of remove the  system.assertEquals('5/31/2020 - 6/6/2020',to.Close_Week__c);  line and let me know the Coverage.
Craig PhoenixCraig Phoenix
We have Success! Thanks for the assist!
Andrew GAndrew G
Oh lord!

My assert fails , so lets just remove it!?!?

The issue why you have the Null in your assert message is that you need to grab the inserted record so that you can test the value that has been populated by the code that you are running.  The test record you have created is held in memory and therefore that field is blank / null / not completed.  The record that is written to disc will have the field populated as the code will update the field and then the field is saved.
 
test.startTest();
insert to;
test.stopTest();

List<Opportunity> insertedRecords = [SELECT Id, Close_Week__c FROM Opportunity WHERE Id = :to.Id LIMIT 1];

System.assertEquals('5/31/2020 - 6/6/2020',insertedRecords[0].Close_Week__c);
Also, all your DMLs should occur inside the test.start/test.stop functions.  Whilst in triggers it generally doesn't matter too much, but can affect things when doing tests in asynchronous type operations.  Then retrieve the data to be tested using SOQL.


Refer to this thread, near the end is some code and a longer explanation on the behaviours of test records and how asserts function against "in memory records" and "retrieved inserted records"



I should maybe just have a piece of text saved so that I can simply paste it in when I harp on about test code needing asserts.   This desire to achieve only "coverage" without asserts shows a lack of understanding of what test code is really there to do.  Without asserts you have no guarentee that the next piece of code that someone inserts in your environment does break existing code.


Regards
Andrew


 
Andrew GAndrew G
realised i missed the link to that thread

https://developer.salesforce.com/forums/ForumsMain?id=9062I000000IKZFQA4

 
Craig PhoenixCraig Phoenix
Thanks Andrew for sharing your knowledge! I appreciate it and this helps me understand the test class more and now I know that asserts are very good to have working to prevent future issues.