+ Start a Discussion
Sammy7Sammy7 

Test class for send email fail

Hi, 
 Im getting the following error and cannot figure out why: 

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

Class.email_class.send: line 48, column 1
Class.TestquoteEmailclass.sendEmailTestMethod: line 47, column 1

Below is my test class: 
@isTest
public class TestquoteEmailclass {
    @isTest static void sendEmailTestMethod(){
    
        Product2 prod = new Product2(Name = 'SLA: Bronze', IsActive = true);
        insert prod;
        PricebookEntry pbe=new PricebookEntry(unitprice=0.01,Product2Id=prod.Id, Pricebook2Id=Test.getStandardPricebookId(), IsActive= true); 
        insert pbe; 
        Account acc = new Account (name='Acme');
        insert acc;
        Opportunity opp= new Opportunity (name='Testopp', Accountid=acc.id, CloseDate= date.today(), StageName='Closed Won', Pricebook2id=Test.getStandardPricebookId());
        insert opp; 
        OpportunityLineItem oppLine = new OpportunityLineItem( pricebookentryid=pbe.Id,TotalPrice=2000, Quantity = 2,Opportunityid = opp.Id);
        insert oppLine;       
        Quote q= new Quote (Name='Testq', Opportunityid=opp.id, QuotetoInvoice__c= True,  Pricebook2id=Test.getStandardPricebookId());
        insert q;
    
     System.currentPagereference().getParameters().put('id',q.id);
     Attachment objAtt = new Attachment();
     objAtt.Name = 'Test';
     objAtt.body = Blob.valueof('string');
     objAtt.ParentId = q.Id;
     insert objAtt;

         ApexPages.StandardController sc =new ApexPages.StandardController(q); 
        email_class ec=new email_class (sc);
        ec.ToAddresses='test@gmail.com';
         ec.CCAddresses='test2@gmail.com';
        ec.emailCC= 'test3@gmail.com';
        ec.email_body='test1111111';
        ec.subject='test22222';
        
         Messaging.InboundEmail email = new Messaging.InboundEmail();  
         Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();
        email.plainTextBody = 'This should become a note';
        email.fromAddress ='test@test.com';
        String contactEmail = 'jsmith@salesforce.com';
        email.ccAddresses = new String[] {'Jon Smith <' + contactEmail + '>'};
        email.subject = 'Dummy Account Name 123';

        ec.send();

}
}

And my controller:
public class email_class{
        
    Public string ToAddresses {get;set;}
    Public string CCAddresses {get;set;}
    Public string quoteId {get;set;}
    Public string subject {get;set;}
    public string email_body {get;set;}
    public string emailTo {get;set;}
    public string emailCC {get;set;}
     public  string [] ccaddress;   
              
        
        
        public email_class(ApexPages.StandardController controller) {
                quoteId = ApexPages.currentPage().getParameters().get('id');
    }
        
    Public PageReference send(){

                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); // set the to address
                mail.setToAddresses(new String[] {emailTo}); 
               // mail.setCCAddresses(new String[] {emailCC});   //set the cc address
                   
        if(emailCC != null && emailCC.trim() != '')
        {
        ccaddress = emailCC.split(',',0);
        mail.setCCAddresses(ccaddress);}
                                                              
   
                mail.setSubject(subject);
                mail.setBccSender(false);
                mail.setUseSignature(false);
                mail.setPlainTextBody(email_body);
               

                List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();

                for (Attachment a : [select Name, Body, BodyLength from Attachment where ParentId = :quoteId]){  // Add to attachment file list  
                        Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();  
                        efa.setFileName(a.Name); 
                        efa.setBody(a.Body); 
                        fileAttachments.add(efa);
                }
                mail.setFileAttachments(fileAttachments);// Send email
                Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
                return null;
        }
}

Any help is appreciated !
Best Answer chosen by Sammy7
Sammy7Sammy7
Forgot to pass "emailTo" DOH !

All Answers

Sammy7Sammy7
Forgot to pass "emailTo" DOH !
This was selected as the best answer
Prathyu PrathyushaPrathyu Prathyusha
Hello 
I am not getting code coverage for this class..anyone please help me
Class:
global class MERCVerificationServiceBatch implements Database.Batchable<sObject>, Database.AllowsCallouts {
    
    String query;
     Set<String> Loyalty_StatusLst;
    global MERCVerificationServiceBatch() {
        Loyalty_StatusLst = new Set<String>{Constants.LOYALTY_AVAILED ,Constants.LOYALTY_AVAILABLE};
        query = 'SELECT Id,Application_Id__c,Is_Customer_Interested__c,Loyalty_Status__c,MCM_Authorized__c  FROM genesis__Applications__c where genesis__CL_Product__r.Category__c = \'MFI\' and MCM_Authorized__c= false and Loyalty_Status__c IN :Loyalty_StatusLst';        
    }
    
    global Database.QueryLocator start(Database.BatchableContext BC) {
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, List<genesis__Applications__c> scope) {
        //try{
            List<genesis__Applications__c> applicationLst =  MERCVerificationService.sendRequest(scope); 
            System.debug('1#####' + applicationLst);
            List<genesis__Applications__c> childAppLst = MERCVerificationService.updateChildApplications(applicationLst);
            System.debug('2#####' + childAppLst);
            if(!childAppLst.isEmpty()){
                GroupLoanService.MCMRenewalUpdateRequest req = new GroupLoanService.MCMRenewalUpdateRequest();
                for(genesis__Applications__c app : childAppLst){
                    GroupLoanService.cls_UpdateApplications applicationObj = new GroupLoanService.cls_UpdateApplications();
                    applicationObj.Application_Id = app.Application_Id__c ;
                    applicationObj.loanOnbordingStatus = Constants.LOYALTY_DISBURSEMENT_STATUS;
                    applicationObj.losId = app.Id;
                    applicationObj.disbursedDate = app.LMS_System_Date__c != null ? app.LMS_System_Date__c.format() : System.today().format();
                    req.Applications.add(applicationObj);
                }
                GroupLoanService.sendRequest(req);
                update childAppLst;
            }
            update applicationLst;
        //}catch(Exception e){
          //  System.debug('Exception occurs' + e);
        //}
    
    }
    
    global void finish(Database.BatchableContext BC) {
        
    }
    
}


Test Class: 
@isTest
Public class MERCVerificationServiceBatchTest {
            
            Public static testMethod void test() {
            
            List<genesis__Applications__c> applicationLs = new  List<genesis__Applications__c>();
            genesis__Applications__c gensis= new genesis__Applications__c();
            gensis.Application_Id__c='A12345678912345678';
            gensis.Is_Customer_Interested__c='MERC';
            gensis.Loyalty_Status__c='Loyalty Available';
            gensis.MCM_Authorized__c=false;
            gensis.genesis__Loan_Amount__c=98976;
            applicationLs.add(gensis);
            Insert applicationLs;
            System.debug('genesis__Applications__c===> '+applicationLs); 
            List<genesis__Applications__c> applicationLs1=[Select Application_Id__c,Is_Customer_Interested__c,Loyalty_Status__c,MCM_Authorized__c,genesis__Loan_Amount__c from genesis__Applications__c];
            Test.startTest();
            MERCVerificationServiceBatch MERC = new MERCVerificationServiceBatch();
            Id batchJobId=Database.executeBatch(MERC);
            Test.stopTest();
            }
}