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
Harjeet Singh 28Harjeet Singh 28 

Test Class Error:System.EmailException: SendEmail failed. First exception on row 0; first error: INVALID_EMAIL_ADDRESS, Email address is invalid: null: [toAddresses, null]

Hi All,

I have been stuck in test class and not getting a way to solve the issue.
I have a VF page and controller. VF page is basically an input form where an user can fill up their information and Save.Once Save the controller will exceute and save the record to a custom object.In input form I have an input field where user can key in their email address.Upon save an email should go to the email address which has been specified in email input field.Functionality is working fine though the issue is with the test class.I understand to test email messaging we need to ensure we are inserting the correct data/record which I am doing but upon running the test class I am getting error : System.EmailException: SendEmail failed. First exception on row 0; first error: INVALID_EMAIL_ADDRESS, Email address is invalid: null: [toAddresses, null]
Below is a part from my VF page:
<apex:page standardController="Driver_Survey__c" extensions="SurveyForDriverController" sidebar="false" lightningStylesheets="true">
    
    
    <apex:form > 
       
        <apex:pageBlock mode="edit" >
            <apex:pageBlockSection columns="1" collapsible="false" title="Driver Information"  >
                <apex:inputField label="Name" value="{!survey.Name__c}" required="true"/>
                <apex:inputField label="Mobile" value="{!survey.Mobile__c}" required="true" />
                <apex:inputField label="Email" value="{!survey.Email__c}" required="true" />
                	
  
            </apex:pageBlockSection>
          
            <apex:pageBlockButtons >

                <apex:commandButton value="Save" action="{!doFullSave}"/>
                  
                    <apex:commandButton value="Cancel" action="{!doCancel}" immediate="true"/>
           
            </apex:pageBlockButtons> 
        </apex:pageBlock>

    </apex:form>
</apex:page>

Below is the Save function snippets:
public class SurveyForDriverController{

    public Driver_Survey__c survey{get;set;}

    public SurveyForDriverController(ApexPages.StandardController controller){
         survey=new Driver_Survey__c();
      
    }
    public PageReference doFullSave(){
        system.debug('message1>>'+survey );
       	insert survey; 
      
  
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.toAddresses = new String[] { survey.Email__c };
            
		system.debug('message110>>'+mail.toAddresses  );
        mail.subject = 'Subject Test Message';
        //mail.plainTextBody = 'This is a test mail';
        String body = 'Hi \n  ';
       
        body += + survey.Name__c+ '<br><br>' ;
        body+= +'Request you to kindly fill in the questionnaire';
     
        mail.setHtmlBody(body);
        Messaging.SingleEmailMessage[] mailss =   new List<Messaging.SingleEmailMessage> {mail};
        Messaging.SendEmailResult[] results = Messaging.sendEmail(mailss);
         if (results[0].success) 
                {
                    System.debug('The email was sent successfully.');
                } else 
                {
                    System.debug('The email failed to send: ' + results[0].errors[0].message);
                }
       
        PageReference pageRef = new PageReference('/'+survey.Id);
        pageRef.setRedirect(true);
        return pageRef;
        }
    public PageReference doCancel(){
        PageReference pageRef = new PageReference('/');
            pageRef.setRedirect(true);
            return pageRef;
    }
   
}

Below is my test clas:
@isTest
public class TestSurveyForDriverController {

    
     static testMethod void test () {
         
       Driver_Survey__c driverSurvey=new Driver_Survey__c();
        driverSurvey.Customer_Experience__c='6';
        driverSurvey.Email__c='test@test.com';
        driverSurvey.Expected_Earnings_Weekly__c=10000;
        driverSurvey.How_long_have_you_been_working_there__c=6;
        driverSurvey.Will_you_be_planning_to_drive_for_Grab__c='Yes';
        driverSurvey.Kind_of_car_are_you_using_Rental_Car__c='Honda City';
        driverSurvey.Name='testuser1';
        driverSurvey.Name__c='testuser1';
        driverSurvey.Customer_Experience__c='All of the Above';
          insert driverSurvey;

       ApexPages.StandardController ctlr = new ApexPages.StandardController(driverSurvey);
       GrabSurveyForDriverController grabController=new GrabSurveyForDriverController(ctlr);

        grabController.doFullSave();
         grabController.doCancel();

    }
}

I am passing correct Email while creating the survey record but test class showing invalid toAddress,null

Any help would be greatly appreciated

Kindly help

Many thanks in advance​​​​​​​​​​​​​​​​​​​​​
Best Answer chosen by Harjeet Singh 28
Neha AggrawalNeha Aggrawal
Hi Harjeet,

Please update the test class to this:
 
@isTest
public class TestSurveyForDriverController {

    
     static testMethod void test () {
         
       Driver_Survey__c driverSurvey=new Driver_Survey__c();
      

       ApexPages.StandardController ctlr = new ApexPages.StandardController(driverSurvey);
       GrabSurveyForDriverController grabController=new GrabSurveyForDriverController(ctlr);
Test.startTest();
       grabController.survey.Customer_Experience__c='6';
        grabController.survey.Email__c='test@test.com';
        grabController.survey.Expected_Earnings_Weekly__c=10000;
        grabController.survey.How_long_have_you_been_working_there__c=6;
        grabController.survey.Will_you_be_planning_to_drive_for_Grab__c='Yes';
        grabController.survey.Kind_of_car_are_you_using_Rental_Car__c='Honda City';
        grabController.survey.Name='testuser1';
        grabController.survey.Name__c='testuser1';
        grabController.survey.Customer_Experience__c='All of the Above';
        grabController.doFullSave();
         grabController.doCancel();
Test.stopTest();

    }
}

Let me know if this helps.
Thanks.

I hope you find the above solution helpful.
Thanks and Regards, 
Neha Aggrawal
www.initaura.com - Everything Salesforce (https://initaura.com)

 

All Answers

Neha AggrawalNeha Aggrawal
Hi Harjeet,

Please update the test class to this:
 
@isTest
public class TestSurveyForDriverController {

    
     static testMethod void test () {
         
       Driver_Survey__c driverSurvey=new Driver_Survey__c();
      

       ApexPages.StandardController ctlr = new ApexPages.StandardController(driverSurvey);
       GrabSurveyForDriverController grabController=new GrabSurveyForDriverController(ctlr);
Test.startTest();
       grabController.survey.Customer_Experience__c='6';
        grabController.survey.Email__c='test@test.com';
        grabController.survey.Expected_Earnings_Weekly__c=10000;
        grabController.survey.How_long_have_you_been_working_there__c=6;
        grabController.survey.Will_you_be_planning_to_drive_for_Grab__c='Yes';
        grabController.survey.Kind_of_car_are_you_using_Rental_Car__c='Honda City';
        grabController.survey.Name='testuser1';
        grabController.survey.Name__c='testuser1';
        grabController.survey.Customer_Experience__c='All of the Above';
        grabController.doFullSave();
         grabController.doCancel();
Test.stopTest();

    }
}

Let me know if this helps.
Thanks.

I hope you find the above solution helpful.
Thanks and Regards, 
Neha Aggrawal
www.initaura.com - Everything Salesforce (https://initaura.com)

 
This was selected as the best answer
Harjeet Singh 28Harjeet Singh 28
Many thanks Neha. I got what and where I was doing mistake. Thanks for highlighting the same
Neha AggrawalNeha Aggrawal
Most Welcome Harjeet,
Please mark the question as resolved.
Thanks.
Sara MarianecciSara Marianecci
@Neha Aggrawal  : sorry can you help me?  SendEmail failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Add a recipient to send an email.: [] I have this error


@IsTest
public class Test_BatchSendEmailNotification {
@testSetup
 static void setup() {
   
    List<Contact> contatti= new List<Contact>();
   Id RecordTypeResId = Schema.SObjectType.Account.getRecordTypeInfosByDeveloperName().get('Reseller').getRecordTypeId();
   Id RecordTypeWalletId = Schema.SObjectType.Wallet__c.getRecordTypeInfosByDeveloperName().get('Reseller_Wallet').getRecordTypeId();
   Id BillingEntityId = Schema.SObjectType.Account.getRecordTypeInfosByDeveloperName().get('Billing_Entity').getRecordTypeId();
   
   Account billingE = new Account(Name = 'Konnect Africa RDC', RecordTypeId = BillingEntityId, CurrencyISOCode = 'USD', Number_of_Terminal_Activated__c=1, timezone__c = 'Africa/Brazzaville');
        insert billingE;  
   
   //account di contatto 1 e 2
   Account acc=new Account(Name='Reseller',Notifications_Email__c=true,Account_Type__c='Reseller',RecordTypeId=RecordTypeResId,BillingEntity__c=billingE.Id);
   insert acc;
   Id account_resId = [SELECT id, Name From Account WHERE Name = 'Reseller'].id;
 
   
   //contatti 1 e 2
   Contact contact_res1 = new Contact(Main_Contact__c=true ,LastName = 'Res', AccountId= account_resId,email ='test23f456a71a213@test5s4sd.com',Notifications_Email__c=true,Contact_ext_Id__c ='b8280a1d',Preferred_Language__c='English'); 
   Contact contact_res2 = new Contact(LastName = 'Res2', AccountId= account_resId,email ='test23f456a71a213@test5s42d.com',Notifications_Email__c=true,Contact_ext_Id__c ='b8280a2d',Preferred_Language__c='English');   
   contatti.add(contact_res1);
   contatti.add(contact_res2);
   insert contatti;
     
   Id resellerId = [SELECT Id FROM Profile WHERE Name = 'Reseller Admin Basic' LIMIT 1].id;
   Id contact_resId1 = [SELECT id, LastName From Contact WHERE LastName = 'Res'].id;
   Id contact_resId2 = [SELECT id, LastName From Contact WHERE LastName = 'Res2'].id;
   
   //user 1
    User user_res = new User(LastName = 'ResTest', alias = 'restest', Email= 'resellerTest@gmail.com', Username = 'resellerTest@gmail.com'    ,ProfileId=resellerId  , ContactId=contact_resId1, TimeZoneSidKey='America/Los_Angeles', LocaleSidKey='en_US', EmailEncodingKey='ISO-8859-1', LanguageLocaleKey='en_US' );
    insert user_res;
     
   //user 2
    User user_res2 = new User(LastName = 'ResTest2', alias = 'restest2', Email= 'resellerTest2@gmail.com', Username = 'resellerTest2@gmail.com'    ,ProfileId=resellerId  , ContactId=contact_resId2, TimeZoneSidKey='America/Los_Angeles', LocaleSidKey='en_US', EmailEncodingKey='ISO-8859-1', LanguageLocaleKey='en_US' );
    insert user_res2;
    Id user_resId = [Select Id from User WHERE Profile.Name='Reseller Admin Basic' AND isActive=true LIMIT 1].Id;
   
   //wallet 1
      Wallet__c wallet_res = new Wallet__c(RecordTypeId = RecordTypeWalletId, Amount__c = 13, Threshold_Amount__c = 220, OwnerId = user_resId, Account__c= account_resId);   
    insert wallet_res;
      
     
    contact_res1.Preferred_Language__c='Francais';
     update contact_res1;
     
    contact_res2.Preferred_Language__c='English';
     update contact_res2;
     
 }

@isTest
    static void BatchSendEmailNotification(){  
   
       List<Wallet__c> listaw=[SELECT Id,Amount__c,Account__c,Account__r.Notifications_Email__c,Account__r.Name,Account__r.Account_Type__c,Account__r.BillingEntity__r.Name
                                         FROM Wallet__c
                                         WHERE  Account__c!= null AND Account__r.Notifications_Email__c=TRUE AND Account__r.Account_Type__c='Reseller'];
       
      System.debug('lista wallet: --_>' +listaw);
        
      List<Contact> listac=[SELECT id, Name, Account.Notifications_Email__c,Preferred_Language__c,
                                      AccountId, Email, main_contact__c
                                     FROM Contact 
                                     WHERE Name='Res' OR Name='Res2' OR Notifications_Email__c=true];
        
    
        Test.startTest();       
       
           Id batchJobId = Database.executeBatch(new BatchSendEmailNotification(),200);
          System.debug('inviata email');
        
        Test.stopTest();
    }         
}