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 line 9, 12 and 14 since these are the three it is telling me is failing.
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!
catch
blocks. They are going to make your debugging process much more difficult, yield false positives, and potentially harm user data.CloseDateWeek__c
is presumably a custom setting - you need to mock these (DML insert) in the test class; custom settings are not considered as metadata and hence don't exist in a test context