In this tutorial, I will explain how to create a unit test for a simple Apex class in Salesforce. Follow the below steps to create a simple Test class for Apex Class.
Step 1) In the Developer Console, click File | New | Apex Class, and enter VerifyDate for the class name, and then click OK.
Step 2) Replace the default class body with the following.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | 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; } } |
Step 3) Press Ctrl+S to save your apex class.
Step 4) Repeat the previous steps to create the TestVerifyDate class. Add the following for this class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | @isTest private class TestVerifyDate{ @isTest static void testDt1GtrDt2(){ Date d2 = system.today(); Date d1 = d2.addDays(10); Date dt = VerifyDate.CheckDates(d1, d2); Date testDt = Date.newInstance(2017, 7, 31); System.assertEquals(dt, testDt); } @isTest static void testDt2Within30dayOfDt1(){ Date d1 = system.today(); Date d2 = d1.addDays(10); Date dt = VerifyDate.CheckDates(d1, d2); System.assertEquals(dt, d2); } } |
Reference: Click here
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.