+ Start a Discussion

Test Coverage of date-based code

I am setting an opportunity closing date as being 90 days from today ( date.today( ) ).


At a later point I create a string with the month name of the closing date, using the following code:

if (NewOpp.CloseDate.month() == 1) {monthName = 'Jan';}
 174	   // else if (NewOpp.CloseDate.month() == 2) {monthName = 'Feb';}
 175	   // else if (NewOpp.CloseDate.month() == 3) {monthName = 'Mar';}
 176	   // else if (NewOpp.CloseDate.month() == 4) {monthName = 'Apr';}
 177	   // else if (NewOpp.CloseDate.month() == 5) {monthName = 'May';}
 178	   // else if (NewOpp.CloseDate.month() == 6) {monthName = 'Jun';}
 179	   // else if (NewOpp.CloseDate.month() == 7) {monthName = 'Jul';}
 180	   // else if (NewOpp.CloseDate.month() == 8) {monthName = 'Aug';}
 181	   // else if (NewOpp.CloseDate.month() == 9) {monthName = 'Sep';}
 182	   // else if (NewOpp.CloseDate.month() == 10) {monthName = 'Oct';}
 183	   // else if (NewOpp.CloseDate.month() == 11) {monthName = 'Nov';}
 184	   // else {monthName = 'Dec';}

 The problem is that when I test the code it comes below 75% coverage,

given that we are in October and the close date of the next opportunity is in January.


How can I modify the test program to get full coverage? Is there a way to simulate

a system time for test purposes?


       Thank you

Rahul SharmaRahul Sharma

A way is to insert the opportunity record with closedate month as Jan then call this method.

then simply keep on updating the closedate to various other months and call this method recpectively.


Suppose your this if condition is in your method name,

then use code like this:


Opportunity o = new Opportunity(Name='Test Opp 1', Stage='Passed', CloseDate=date.newinstance(2011, 1, 1));
insert o;
o.closeDate=date.newinstance(2011, 2, 1);
update o;
repeat until 12th month
o.closeDate=date.newinstance(2011, 12, 1);
update o;

 hope it helps.




Thank you, Rahul, but your suggestion doesn't work in my case.


To clarify:


I have a trigger that closes one opportunity and opens a new one.

It uses the TODAY value to create a close date for the new opportunity (TODAY + 90).

This is done regardless of the value of the closing date of the first opportunity.


The test program creates the first opportunity that will be closed by the trigger

with another one being opened. The closing date of the opportunity is

not being used for the creation of the new one.


To have full coverage, I would have to have the method date.today( ) return

different values, spaced one month apart.


Any suggestions?