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
David Vickers 44David Vickers 44 

Create a unit test for a simple Apex trigger How do i access the getmessages() correctly?

I am a beginner with coding and looking for help

The code I have below works for getting 100% coverage and passes the trailhead evaluation however I also wanted to assert that the Error message is correct.

because I wanted to set up all test data outside of the starttest() and I wanted to check and valid insert as well as a invalid one I need to write the saveresults to a list. Everything works fine untill i tried to access the  error messages.
I have played with every variation but cannot figure out the syntax

system.debug(r1.getErrors());  gives me  DEBUG|(Database.Error[getFields=();getMessage=The Last Name "INVALIDNAME" is not allowed for DML;getStatusCode=FIELD_CUSTOM_VALIDATION_EXCEPTION;])

system.debug(r1.getErrors().getMessage);  doesn't compile " Initial term of field expression must be a concrete SObject: List<Database.Error>"
system.debug(r1.getErrors().getMessage()); doesn't  Method does not exist or incorrect signature: [List<Database.Error>].getmessage()

And so my tries Have gone on!

how do I get the getMessage field from the getErrors?

 
@istest
private class TestRestrictContactByName {
    @isTest Static void TestRestictedname(){
        List<contact> testcontacts = New List<contact>();
        contact c0 = new contact(LastName = 'Testcontact');
        testcontacts.add(c0);
        Contact c1 = new contact(LastName = 'INVALIDNAME');
        testcontacts.add(c1);
        Test.startTest(); 
        Database.SaveResult[] srList = Database.insert(testcontacts, false); 
        Test.stopTest();
        Database.SaveResult R0 = srlist[0];
        Database.SaveResult R1 = srlist[1];
        
        System.assert(r0.isSuccess());
        System.assert(!r1.isSuccess());
                      
                      }
                      }

 
Best Answer chosen by David Vickers 44
Amit Chaudhary 8Amit Chaudhary 8

Please check below post for same issue
1) https://developer.salesforce.com/forums/?id=906F0000000BNjqIAG
2) https://developer.salesforce.com/forums/?id=906F0000000BQwoIAG

you can try below code
@isTest
public class TestRestrictContactByname {
    
    @isTest static void TestContactWithInvalidNameNotInserted(){
        
        String inputLastName = 'INVALIDNAME';
        Contact newContact = new Contact(LastName= inputLastName);	    
        
        Test.startTest();
        try{
            insert newContact;
        }
        catch (DmlException dmlEx) {
        	
        	// Verify (Assert)
        	// In this case the insert should have been stopped by the trigger,
        	// so we need to verify that we got a dml exception (and specifically that we got the error message
            // that we were expecting).
        	String expectedMessage = 'The Last Name "'+ newContact.LastName+'" is not allowed for DML';
            System.assertEquals(expectedMessage, dmlEx.getDmlMessage(0));
        }
        Test.stopTest();
    }
}

Sample code 2:-
@isTest
private class TestRestrictContactByName {

    @isTest static void metodoTest() 
    {
        Contact c = new Contact(LastName = 'INVALIDNAME');
  
       
        Database.SaveResult result = Database.insert(c, false);
      
       
        System.assert(!result.isSuccess());
        System.assert(result.getErrors().size() > 0);
        System.assertEquals('The Last Name "INVALIDNAME" is not allowed for DML',
                             result.getErrors()[0].getMessage());


        
    }
    
}


Let us know if this will help you

Thanks
Amit Chaudhary
 

All Answers

Nicola GrisctiNicola Griscti
So based on that error message, you probably can only access standard salesforce errors which are in some salesforce error objects with that method.

The way that I completed this challenge, was to test the save result was equal to the error message exactly which is outputted there - because it is custom and you know what it is - and it doesn't appear to be a "proper" error standard message such as "can't delete related xyz" or "can't insert because there are required fields" something like this...

I think this information will help you complete the challenge. But you may want to try and test the same code when checking for a standard error message. 
Amit Chaudhary 8Amit Chaudhary 8

Please check below post for same issue
1) https://developer.salesforce.com/forums/?id=906F0000000BNjqIAG
2) https://developer.salesforce.com/forums/?id=906F0000000BQwoIAG

you can try below code
@isTest
public class TestRestrictContactByname {
    
    @isTest static void TestContactWithInvalidNameNotInserted(){
        
        String inputLastName = 'INVALIDNAME';
        Contact newContact = new Contact(LastName= inputLastName);	    
        
        Test.startTest();
        try{
            insert newContact;
        }
        catch (DmlException dmlEx) {
        	
        	// Verify (Assert)
        	// In this case the insert should have been stopped by the trigger,
        	// so we need to verify that we got a dml exception (and specifically that we got the error message
            // that we were expecting).
        	String expectedMessage = 'The Last Name "'+ newContact.LastName+'" is not allowed for DML';
            System.assertEquals(expectedMessage, dmlEx.getDmlMessage(0));
        }
        Test.stopTest();
    }
}

Sample code 2:-
@isTest
private class TestRestrictContactByName {

    @isTest static void metodoTest() 
    {
        Contact c = new Contact(LastName = 'INVALIDNAME');
  
       
        Database.SaveResult result = Database.insert(c, false);
      
       
        System.assert(!result.isSuccess());
        System.assert(result.getErrors().size() > 0);
        System.assertEquals('The Last Name "INVALIDNAME" is not allowed for DML',
                             result.getErrors()[0].getMessage());


        
    }
    
}


Let us know if this will help you

Thanks
Amit Chaudhary
 
This was selected as the best answer
David Vickers 44David Vickers 44
Here is my final code Amit. 

A little differnt to yours but thanks for line 14 in your sample code 2 that was what I was looking for
 
@istest
private class TestRestrictContactByName {
    @isTest Static void TestRestictedname(){
        List<contact> testcontacts = New List<contact>();
        contact c0 = new contact(LastName = 'Testcontact');
        testcontacts.add(c0);
        Contact c1 = new contact(LastName = 'INVALIDNAME');
        testcontacts.add(c1);
        Test.startTest(); 
        Database.SaveResult[] srList = Database.insert(testcontacts, false); 
        Test.stopTest();
        Database.SaveResult R0 = srlist[0];
        Database.SaveResult R1 = srlist[1];
        System.assertequals(r1.getErrors()[0].getmessage(),'The Last Name "INVALIDNAME" is not allowed for DML');
        System.assert(r0.isSuccess());
        System.assert(!r1.isSuccess());
                      
                      }
                      }

 
Ian Lin 386Ian Lin 386
This code also works and let you complete trailhead challenge with 100% code coverage

@isTest
public class TestRestrictContactByName {
    @isTest static void testName(){
    Contact con = new Contact(FirstName='XYZ', LastName='INVALIDNAME');
    insert con;
    }
}
Alyssa YanezAlyssa Yanez
Thank you for this! I was looking for a simpler example(: