+ Start a Discussion
Narasimha Reddy 33Narasimha Reddy 33 

Test class for Verify date

public class VerifyDate {
//method to handle potential checks against two dates
public static Date CheckDates(Date date1, Date date2) {
//if date2 is within the next 30 days of date1, use date2. Otherwise use the end of the month
if(DateWithin30Days(date1,date2)) {
return date2;
} else {
return SetEndOfMonthDate(date1);
}
}
//method to check if date2 is within the next 30 days of date1
private static Boolean DateWithin30Days(Date date1, Date date2) {
//check for date2 being in the past
if( date2 < date1) { return false; }
//check that date2 is within (>=) 30 days of date1
Date date30Days = date1.addDays(30); //create a date 30 days away from date1
if( date2 >= date30Days ) { return false; }
else { return true; }
}
//method to return the end of the month of a given date
private static Date SetEndOfMonthDate(Date date1) {
Integer totalDays = Date.daysInMonth(date1.year(), date1.month());
Date lastDay = Date.newInstance(date1.year(), date1.month(), totalDays);
return lastDay;
}
}

I need test class for this class.Please provide me
Best Answer chosen by Narasimha Reddy 33
Narasimha Reddy 33Narasimha Reddy 33
Hi Amit,
Thanks for Your code.Its Working fine.

Thanks,
Narasimha.

All Answers

Amit Chaudhary 8Amit Chaudhary 8
Please try below code.
 
@isTest 
public class VerifyDateTest 
{
    static testMethod void testMethod1() 
    {
        Date d = VerifyDate.CheckDates(System.today(),System.today()+1);
        Date d1 = VerifyDate.CheckDates(System.today(),System.today()+60);
    }
}


Please check below blog for more information in test classess:-
http://amitsalesforce.blogspot.in/2015/06/best-practice-for-test-classes-sample.html

Please follow below salesforce Best Practice for Test Classes :-

1. Test class must start with @isTest annotation if class class version is more than 25
2. Test environment support @testVisible , @testSetUp as well
3. Unit test is to test particular piece of code working properly or not .
4. Unit test method takes no argument ,commit no data to database ,send no email ,flagged with testMethod keyword .
5. To deploy to production at-least 75% code coverage is required 
6. System.debug statement are not counted as a part of apex code limit.
7. Test method and test classes are not counted as a part of code limit
9. We should not focus on the  percentage of code coverage ,we should make sure that every use case should covered including positive, negative,bulk and single record .
Single Action -To verify that the the single record produces the correct an expected result .
Bulk action -Any apex record trigger ,class or extension must be invoked for 1-200 records .
Positive behavior : Test every expected behavior occurs through every expected permutation , i,e user filled out every correctly data and not go past the limit .
Negative Testcase :-Not to add future date , Not to specify negative amount.
Restricted User :-Test whether a user with restricted access used in your code .10. Test class should be annotated with @isTest .
11 . @isTest annotation with test method  is equivalent to testMethod keyword .
12. Test method should static and no void return type .
13. Test class and method default access is private ,no matter to add access specifier .
14. classes with @isTest annotation can't be a interface or enum .
15. Test method code can't be invoked by non test request .
16. Stating with salesforce API 28.0 test method can not reside inside non test classes .
17. @Testvisible annotation to make visible private methods inside test classes.
18. Test method can not be used to test web-service call out . Please use call out mock .
19. You can't  send email from test method.
20.User, profile, organization, AsyncApexjob, Corntrigger, RecordType, ApexClass, ApexComponent ,ApexPage we can access without (seeAllData=true) .
21. SeeAllData=true will not work for API 23 version eailer .
22. Accessing static resource test records in test class e,g List<Account> accList=Test.loadData(Account,SobjectType,'ResourceName').
23. Create TestFactory class with @isTest annotation to exclude from organization code size limit .
24. @testSetup to create test records once in a method  and use in every test method in the test class .
25. We can run unit test by using Salesforce Standard UI,Force.com IDE ,Console ,API.
26. Maximum number of test classes run per 24 hour of period is  not grater of 500 or 10 multiplication of test classes of your organization.
27. As apex runs in system mode so the permission and record sharing are not taken into account . So we need to use system.runAs to enforce record sharing .
28. System.runAs will not enforce user permission or field level permission .
29. Every test to runAs count against the total number of DML issued in the process .


Please let us know if this post will help you

Thanks,
Amit Chaudhary
Narasimha Reddy 33Narasimha Reddy 33
Hi Amit,
Thanks for Your code.Its Working fine.

Thanks,
Narasimha.
This was selected as the best answer
Veronika LuzicovaVeronika Luzicova
Hi all,

I have tried my own code, the tests were all complete and working fine, no failures but the coverage still says 0. 

I also tried the above codes and others from other questions, all the tests work but the coverage still says 0%. Any advice? 

Thanks.
Hamsa JeganathanHamsa Jeganathan
Veronika - Were you able to get past the test coverage issue? Even with the sample test class TemperatureConverterTest I still show zero coverage for the class TemperatureConverter. I made sure I ran the test multiple times, cleared out the test results and re ran tests. No luck still. I am on version 35. Would love to know if you were able to get this fixed.
Veronika LuzicovaVeronika Luzicova
Hi Hamsa - Sorry, but I never figured out how to fix this issue, I was hoping somebody here would know what to do.... If I manage to find the solution I will post it here. Veronika Luzicova Consultant Arcus Global Ltd www.arcusglobal.com Mobile: 07920 520355
Veronika LuzicovaVeronika Luzicova
So somehow I managed to fix this, not really sure what helped exactly though.

I didn't change anything about the code. What I have done, is made sure that I have have the "Author Apex" system permissions. That was the first thing, but then when I ran the test via Developer Console - no change, still 0%.

Then I tried running the tests via Setup -> Apex Test Execution. I ran all of the tests (I had two other ones available). The test we are talking about was successfully completed, as before, but when I checked the coverage in the Developer Console it now says 100%. When I open the class, I still don't see highlighted rows - blue or red, based on the coverage, just the normal background, but the coverage says 100% and Trailhead accepted it.

If anyone has any idea what happened there, please let me know.
Thanks
Veronika
Hamsa JeganathanHamsa Jeganathan
Hi Veronika,

Thank you, that helped. I was able to get the console to show the test coverage after running it from Apex Test Execution. I dont see the highlighted rows either but I was able to get the challenge verified for the trailhead course.

Thanks,
Hamsa
Veronika LuzicovaVeronika Luzicova
Once the coverage is more than 0, if you open the class in the console, top left corner is a picklist saying Coverage. If you pick all tests you will get the highlighted rows :) But you only see it when the test gives more than 0. For 0 it just says None and no highlights are happening. Veronika Luzicova Consultant Arcus Global Ltd www.arcusglobal.com Mobile: 07920 520355
Hamsa JeganathanHamsa Jeganathan
Spot on, thanks again Veronika!
Kishan MalepuKishan Malepu
Hi Veronica,
 I have faced the same problem my code was running perfectly with sucess and all are green mark but when I check the challegege it says code coverage is not 100% 

Whenever you modify your Apex code or  rerun your tests to refresh code coverage results.
A known issue with the Developer Console prevents it from updating code coverage correctly when running a subset of tests. To update your code coverage results, use Test | Run All rather than Test | New Run.
After doing this I have verified my challenge and code coverage are success and 100%.

I hope this will help ohers who is working on challenges :-)

Thanks & Regards,
Kishan


 
Titane PhamTitane Pham
@isTest 
public class TestVerifyDate 
{
    static testMethod void testMethod1() 
    {
        Date d = VerifyDate.CheckDates(System.today(),System.today()+1);
        Date d1 = VerifyDate.CheckDates(System.today(),System.today()+60);
    }
}
Shruti Mathur 59Shruti Mathur 59
Hi, you can try the below code as well. It is robust and in true sense it tests the class methods.

@isTest
public class TestVerifyDate {
    @isTest static void testCheckDatesdate2() {
        Date d1 = VerifyDate.CheckDates(System.today(), System.today()+10);
        System.assertEquals(System.today()+10, d1);
    }
    
    @isTest static void testCheckDatesenddate() {
        Date d2 = VerifyDate.CheckDates(System.today(), System.today()+50);
        Date startDate = System.Date.today().toStartOfMonth(); 
        System.assertEquals(startDate.addMonths(1).addDays(-1), d2);
    }
}
Thomas HThomas H
Thanks Shruti  --- Got complete coverage .... Perfect.

Good thread overall too.
 
Susannah PSusannah P
Thanks Shruti! Great way to get the last day of the end of the month!
Raj OjhaRaj Ojha

Hi Guys, 

This is of the best solution to the Trailhead Apex Testing Part 1 - Challenge. Please feel free to ask questions. 

@isTest
public class TestVerifyDate {
    //potentialcheck
    @isTest static void testCheckDates(){
        Date checkDate = VerifyDate.CheckDates(date.today(),date.today().addDays(20));
        System.assertEquals(Date.newInstance(2018,5,26), checkDate);
    }
    @isTest static void testCheckDates1(){
        Date checkDate = VerifyDate.CheckDates(date.today(),date.today().addDays(30));
        System.assertEquals(Date.newInstance(2018,5,31), checkDate); 
    }
    //checkboolean
    @isTest static void testDateWithin30Days(){
        Date date1 = date.today();
        Date date2 = date.today().addDays(-2);
        Boolean testDate = VerifyDate.DateWithin30Days(date1,date2);
        System.assertEquals(false,testDate);
    }
    @isTest static void testDateWithin30Days1(){
        Date date1 = date.today();
        Date date2 = date.today().addDays(2);
        Boolean testDate = VerifyDate.DateWithin30Days(date1,date2);
        System.assertEquals(true,testDate);
    }
    @isTest static void testDateWithin30Days2(){
        Date date1 = date.today();
        Date date2 = date.today().addDays(2);
        Boolean testDate = VerifyDate.DateWithin30Days(date1,date2);
        System.assertEquals(true,testDate);
    }    
    //return end of date the month
    @isTest static void testSetEndOfMonthDate(){
        Date lastDate = VerifyDate.SetEndOfMonthDate(date.today());
        System.assertEquals(Date.newInstance(2018,5,31),lastDate);
    }
}

Sreenu Reddy 16Sreenu Reddy 16
you get 100% code coverage 
@isTest
public class TestVerifyDate {
  static testMethod void testMethod1()
  {
      Date d  = VerifyDate.CheckDates(System.today(),System.today()+10);
      Date d1 = VerifyDate.CheckDates(System.today(),System.today()+20); 
      Date d2  = VerifyDate.CheckDates(System.today(),System.today()-10);
        
    }
}
sharif.mosharif.mo
This also worked, had to make SetEndOfMonthDate() method Public first.

@isTest
public class TestVerifyDate {
    @isTest static void testDates(){
        Date D1= VerifyDate.CheckDates(System.today(), System.today()+10);
        Date D2 = VerifyDate.CheckDates(System.today(), System.today()+35);
        Date D3 = VerifyDate.SetEndOfMonthDate(System.today());
        System.assertEquals(D1,System.today()+10);
        System.assertEquals(D2,D3);
        
    }
}
Anu Yalamanchi 7Anu Yalamanchi 7
Can someone explain @Shruthi Mathur 59 code?How it's covering 100%?
NILESHKUMAR PATELNILESHKUMAR PATEL
@isTest
Private class VerifyDateTest{
    Static testMethod void testdate(){
        Date d2 = System.today();
        Date d1 = d2.addDays(10);
        
        // Passing two dates to checkDate function
        // Main class should return end of April
        Date dt = VerifyDate.CheckDates(d1,d2);
        Date testDt = Date.newInstance(2019,4,30);
        System.assertEquals(dt,testDt);   
    }
    
    //calling this function and passing two dates
    @isTest static void VerifyDateWithin30Days(){
        Date d1 = system.today();
        Date d2 = d1.addDays(10);
        
        Date dt = VerifyDate.CheckDates(d1,d2);
        System.assertEquals(dt,d2);
    }
}
Rinku ReddyRinku Reddy
This gave 100% code coverage 
@isTest 
private class TestVerifyDate {
    static testMethod void TestVerifyDate() {
        //within 30
        Date date1=system.today();
        Date date2=system.today().addDays(5);
        String returnValue=String.valueOf(VerifyDate.CheckDates(date1,date2));
            
        //not within 30 
        Date date3=system.today();
        Date date4=system.today().addDays(35);        
        String returnValue2=String.valueOf(VerifyDate.CheckDates(date3,date4));
        
        Date date33=system.today().addDays(35);
        Date date43=system.today();        
        String returnValue3=String.valueOf(VerifyDate.CheckDates(date33,date43));
    }
}
Tien Le 488Tien Le 488
@Rinku Reddy, God bless you brother!  I'm so new at this and was just so frustrating trying to get it to work but problems after problems!  With your suggestion, at least now I can go back and dissect why my test didn't work and yours did.  Thanks so much for your help to overcome a blocking/frustrating situation I was in.
jothiraj gnanaprakasamjothiraj gnanaprakasam
@isTest
private class TestVerifyDate {
    @isTest static void testDateWithin30Days() {
        
        Date d = VerifyDate.CheckDates(system.today(), system.today().addDays(20));
        System.assertEquals(d,system.today().addDays(20));
        
        d = VerifyDate.CheckDates(system.today(), system.today().addDays(40));
        Integer totalDays = Date.daysInMonth(system.today().year(), system.today().month());
        Date lastDay = Date.newInstance(system.today().year(), system.today().month(), totalDays);
        System.assertEquals( lastDay, d);
        
        d = VerifyDate.CheckDates(system.today(), system.today().addDays(-2));
        System.assertEquals(lastDay, d);
        
        
    }
  
    }
Celio XavierCelio Xavier
Olá, com este teste eu consegui atingir o 100% da cobertura: 

@isTest
public class TestVerifyDate {
    @isTest static void testCheckDatesdate2() {
        Date date1 = VerifyDate.CheckDates(System.today(), System.today()+1);
        System.assertEquals(System.today()+10, date1);
    }
    
    @isTest static void testCheckDatesenddate() {
        Date date2 = VerifyDate.CheckDates(System.today(), System.today()+60);
        Date startDate = System.Date.today().toStartOfMonth(); 
        System.assertEquals(startDate.addMonths(1).addDays(-1), date2);
    }
}