function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Pallavi GholePallavi Ghole 

Create a unit test for a simple Apex trigger

Hello,
In the exercise "Create a unit test for a simple Apex trigger" , here is the code I wrote and for some reason it keeps giving me an Assertion failed 
@ line 24. Can you please help determine the reason?

@isTest
private class TestRestrictContactByName
 {
    @isTest static void TestMethodRestrictContact() {
        // Test data setup
        // Create an Account and its contact with Last Name = INVALIDNAME
        Account acct = new Account(Name='Test Account');
        insert acct;

List <Contact> contactlist = new List <Contact>();

Contact cont1 = new Contact(FirstName='Test1',LastName='INVALIDNAME',Email='test1@invalid.com',AccountId=acct.Id);
contactlist.add(cont1);
Contact cont2 = new  Contact(FirstName='Test2',LastName='VALIDNAME',Email='test2@valid.com',AccountId=acct.Id);
contactlist.add(cont2);

Test.startTest();
    try {
        insert contactlist;
        }
    Catch (DMLException exp) {
        for(integer i = 0; i < 2; i++) {
    //System.assert(exp.getMessage().contains('The Last Name "'+Contactlist[i].LastName+'" is not allowed for DML'));
    System.assert(exp.getMessage().contains('The Last Name INVALIDNAME is not allowed for DML'));
        }
    }
Test.stopTest();
}
}

 
Best Answer chosen by Pallavi Ghole
Abhishek Raj 23Abhishek Raj 23
Hi,
I guess it is because your assert statement is missing double quotes.  
 System.assert(exp.getMessage().contains('The Last Name "INVALIDNAME" is not allowed for DML'));

All Answers

Khan AnasKhan Anas (Salesforce Developers) 
Hi Pallavi,

Greetings to you!

Please try below code:
@isTest
private class TestRestrictContactByName{
    
    @isTest static void testOne() {
        List<Contact> listOfContacts = new List<Contact>();
        for(integer i = 0; i < 200; i++){
            Contact c = new Contact(FirstName = 'FNAME', LastName = 'INVALIDNAME');
            listOfContacts.add(c);
        }
        try{
            insert listOfContacts;
        }
        catch(DMLException ex){
            for(integer i = 0; i < 200; i++){
                System.assert(ex.getMessage().contains('The Last Name "'+listOfContacts[i].LastName+'" is not allowed for DML'));
            }
        }        
    }    
}

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
Pallavi GholePallavi Ghole
Hi Khan Anas,
Thank you so much for the response, the class you have provided above is the one I have seen in multiple forums. While I can always use that class as a backup I am also trying to understand what is going wrong with the code I have written. Any help would be appreciated!

Regards
Pallavi 
Abhishek Raj 23Abhishek Raj 23
Hi,
I guess it is because your assert statement is missing double quotes.  
 System.assert(exp.getMessage().contains('The Last Name "INVALIDNAME" is not allowed for DML'));
This was selected as the best answer
Pallavi GholePallavi Ghole
Thanks a lot Abhishek Raj 23 - that was it!
Thanks for your help. 
 
Lalit Gupta 37Lalit Gupta 37
Please try below mentioned approach :

@isTest
public class TestRestrictContactByName {

        @isTest static void TestRestrictContactByName()
        {
            Contact con = new Contact(LastName = 'INVALIDNAME');
            test.startTest();
            Database.SaveResult result= database.insert(con,false);
            test.stopTest();
            system.assertEquals('The Last Name INVALIDNAME is not allowed for DML', 
                               result.getErrors()[0].getMessage());

        }
}
Preeti Kant 3Preeti Kant 3
@isTest
public class TestRestrictContactByName {
    @isTest static void TestUpdateContact(){
            //create one contact records
        Contact objContact = new Contact(LastName = 'INVALIDNAME');
        insert objcontact;
        
        //varify test
        Test.startTest();
        Database.saveResult result = Database.insert(objContact,false);
        Test.stopTest();
        //verify
        //In this case deletion should have been stopped by the trigger. 
        System.assert(!result.isSuccess());
        System.assert(result.getErrors().size() > 0);
        System.assertEquals('Cannot update the contact.',result.getErrors()[0].getMessage());
    }    
}
FIRAT DIKMENFIRAT DIKMEN

Usually this problem occurs when the written test is not run. After writing the test, run it at least 1 time and try.

# SOLUTION

1.  In the Developer Console, click **File** | **New** | **Apex Class**, and enter **VerifyDate** for the class name, and then click **OK**.
    
2.  Replace the default class body with the following.

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;
        }
    
    }
 


    
3.  Press Ctrl+S to save your class.
    
4.  In the Developer Console, click **File** | **New** | **Apex Class**, and enter **TestVerifyDate** for the class name, and then click **OK**.
    
5.  Replace the default class body with the following.
    
  

@isTest
    private class TestVerifyDate {
    
        //testing that if date2 is within 30 days of date1, should return date 2
        @isTest static void testDate2within30daysofDate1() {
            Date date1 = date.newInstance(2018, 03, 20);
            Date date2 = date.newInstance(2018, 04, 11);
            Date resultDate = VerifyDate.CheckDates(date1,date2);
            Date testDate = Date.newInstance(2018, 04, 11);
            System.assertEquals(testDate,resultDate);
        }
        
        //testing that date2 is before date1. Should return "false"
        @isTest static void testDate2beforeDate1() {
            Date date1 = date.newInstance(2018, 03, 20);
            Date date2 = date.newInstance(2018, 02, 11);
            Date resultDate = VerifyDate.CheckDates(date1,date2);
            Date testDate = Date.newInstance(2018, 02, 11);
            System.assertNotEquals(testDate, resultDate);
        }
        
        //Test date2 is outside 30 days of date1. Should return end of month.
        @isTest static void testDate2outside30daysofDate1() {
            Date date1 = date.newInstance(2018, 03, 20);
            Date date2 = date.newInstance(2018, 04, 25);
            Date resultDate = VerifyDate.CheckDates(date1,date2);
            Date testDate = Date.newInstance(2018, 03, 31);
            System.assertEquals(testDate,resultDate);
        }  
    }
 


    
6.  Press Ctrl+S to save your class.
    
7.  In the Developer Console, click **Test** | **New Run**.
    
8.  Under **Test Classes**, click **TestVerifyDate**.
    
9.  To add all the test methods in the **TestVerifyDate** class to the test run, click **Add Selected**.
    
10. Click **Run**.
    
11. In the Tests tab, you see the status of your tests as they’re running. Expand the test run, and expand again until you see the list of individual tests that were run. They all have green checkmarks.