+ Start a Discussion
keshin okawakeshin okawa 

Make a Test class for System.Today().month()

I am almost done with my test class and I ended up with 2 lines in my class that are not covered by my test class.

        if(Integer.valueOf(System.Today().month()) - 1 == 0) {
            mMonth = '12';
             mYear = String.valueOf(Integer.valueOf(System.Today().year()) - 1);

         } else {
            mMonth= String.valueOf(Integer.valueOf(System.Today().month()) - 1);
             mYear = String.valueOf(Integer.valueOf(System.Today().year()));
         } 
How do I cover the 2 lines of code ( bold ones )?
Some of my other classes also uses that same lines of code. Thanks!!
Shashikant SharmaShashikant Sharma


The reason why it is not covered is that its month of July and your code taking current dates month which is 7 so 7-1 =>6 . This will be covered in month of January, but then else part wont be covered. To fix it.

You should take a Static Date variable in your actual class

Public static DateToCompareWhileTest;

and change your condition to:

if(Integer.valueOf(System.Today().month()) - 1 == 0 
    || ( Test.isRunningTest() 
         && DateToCompareWhileTest != null
         && DateToCompareWhileTest.month() - 1 == 0 ) ) {

// existing code
}
else {
// existing code
}
 

You can then prepare a test case where DateToCompareWhileTest is a Date of January month.
 

Sudeep DubeSudeep Dube
    if(Integer.valueOf(System.Today().month()) - 1 == 0 || Test.isRunnigTest() ) {
            mMonth = '12';
            mYear = String.valueOf(Integer.valueOf(System.Today().year()) - 1);
            
         } else {
            mMonth= String.valueOf(Integer.valueOf(System.Today().month()) - 1);
             mYear = String.valueOf(Integer.valueOf(System.Today().year()));
         } 
David Holland 6David Holland 6
Sundeep

The error with your code is that it will never cover the second scenario in the tests.

To the original poster, your code would work perfectly fine with the following lines:

DateTime dateOneMonthAgo = System.Today().addMonths(-1);
String mMonth = String.valueOf(dateOneMonthAgo.month());
String mYear = String.valueOf(dateOneMonthAgo.year());
keshin okawakeshin okawa
@Shashikant Sharma...I tried adding it to my class and declared a value of DateToCompareWhileTest in my test class. Sadly, its still the same as before where the 2 lines arent covered.
 
keshin okawakeshin okawa
@David Holland 6. I'm kinda confused how to use your code to solve my problem. Please enlighten me.
David Holland 6David Holland 6
@keshin okawa

This code means you do not need your IF statement anymore, as if the date is 01/01/2016, the variable "dateOneMonthAgo" will automatically equate itself to "01/12/2015", meaning you do not need to manually intervene if the month is January.
David Holland 6David Holland 6
Keshin

If my code fixed your code coverage problem, please accept so that others can see what to do.

Many thanks