0

Class:

global class SendNewAccountEmailBatch implements Database.Batchable<sObject>, Database.Stateful {

    List<string> sendingTo;
    EmailTemplate mailTemplateRcd;
    global Map<Id,String> idEmailMap;
    Map<Id, List<String>> accIdTeamEmailMap;

    public  SendNewAccountEmailBatch(Map<Id,String> idEmailMap, Map<Id, List<String>> accIdTeamEmailMap){
        mailTemplateRcd =[Select id, htmlValue, subject from EmailTemplate where DeveloperName  = 'New_Client_Email_Notification'];
        sendingTo = new List<String>();

        this.accIdTeamEmailMap = accIdTeamEmailMap;
        
        this.idEmailMap = idEmailMap;
        List<EmailToSendNewAcc__mdt> emailToSend = [SELECT Id, Email__c, MasterLabel FROM EmailToSendNewAcc__mdt];
        for (EmailToSendNewAcc__mdt emailAux : emailToSend ){
            sendingTo.add(emailAux.Email__c);
        }
    }
    
    global Database.querylocator start(Database.BatchableContext bc) {
        String accountFields = 'Id,OwnerId,Segmentation__c,Contract_Type__c,ParentName__c,Branch__c,Primary_Account_Contact__r.Address__r.State__r.Name,Valid_Contract__c,Valid_Contract__r.ContractNumber,Primary_Account_Contact__c,Primary_Account_Contact__r.Name,Primary_Account_Contact__r.CPFCNPJ__c,Originator__c,Originator__r.Name,FEE__c,JBFOMandate__c,Owner.Name,Intermediate__c,Intermediate__r.Name,ExtraServices__c,ClientPeculiaritiesReserves__c,ClientPeculiaritiesReservesDetails__c';
        Set<Id> idList = idEmailMap.keySet();
        
        String query = 'SELECT '+accountFields+' FROM Account WHERE Id =:idList';
                
        return Database.getQueryLocator(query);

    }
    
    global void execute(Database.BatchableContext bc, List<Account> records){
        Map<Id,List<String>> accidEmailList = new Map<Id,List<String>>();
        List<AccountTeamMember> accTeamList = [SELECT Id FROM AccountTeamMember where AccountId=: records];

        for (Account accAux: records){
            Messaging.SingleEmailMessage semail = new Messaging.SingleEmailMessage();

            List<String> toAddressList = new List<String>();
            toAddressList = sendingTo;

            if( accIdTeamEmailMap.containsKey(accAux.Id)){
                for(String strAux: accIdTeamEmailMap.get(accAux.Id)){
                    toAddressList.add(strAux);
                }
            }
            
            
            semail.setWhatId(accAux.Id);
            semail.setToAddresses(toAddressList);
            semail.setSubject(mailTemplateRcd.subject);
            semail.setHtmlBody(idEmailMap.get(accAux.Id));

            Messaging.SingleEmailMessage[] messages = new List<Messaging.SingleEmailMessage> {semail};
        
            Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);
            if (results[0].success) {
                System.debug('The email was sent successfully.');
            } else {
                System.debug('The email failed to send: ' + results[0].errors[0].message);
            }
        }
        
    }
    global void finish(Database.BatchableContext bc){
        // execute any post-processing operations
    }

}

Test class:

@isTest
public class SendNewAccountEmailBatchTest {
        static testmethod void SendNewAccountEmailBatchTestMethod() {
        Profile prof = [SELECT Id FROM Profile WHERE Name='System Administrator'];
        User user = new User();
        user.FirstName = 'test1';
        user.LastName = 'test2';
        user.ProfileId = prof.id;
        user.Username = 'testclass@testclass.com';
        user.Email = 'testclass@testclass.com';
        user.LocaleSidKey='en_US';
        user.EmailEncodingKey='UTF-8';
        user.LanguageLocaleKey='en_US';
        user.Alias = 'tscls';
        user.TimeZoneSidKey = 'America/Los_Angeles';
        Insert user;
        
        Account acc = TestDataFactory.createAccount();
        acc.Segmentation__c = 'First';
        acc.OwnerId = user.Id;
        insert acc;
          
    
            Map<Id,String> idEmailMap = new Map<Id,String>();
            idEmailMap.put(user.Id, user.Email);
            Map<Id, List<String>> accIdTeamEmailMap = new Map<Id, List<String>>();
            
            Test.startTest();
            SendNewAccountEmailBatch setot = new SendNewAccountEmailBatch(idEmailMap, accIdTeamEmailMap);
            Database.executebatch(setot);
            Test.stopTest();
            
            User usrResult = [SELECT Id, Email FROM User WHERE Username = 'testclass@testclass.com' ];
            System.assertEquals('testclass@testclass.com', usrResult.Email, 'Email não enviado');
    }

}

I'm with 45% of coverage and I can't cover my execute method. What am I missing?

0

The reason is because neither of your parameters (idEmailMap and accIdTeamEmailMap) are set up with valid values in your test to mimic how the code actually runs or expects. In a test context, it's up to you to set up your data and pass expected values to your methods to run in a similar context to what it deals with in production.

idEmailMap seems to be a map of html email body (value) by Account Id (key). I assume this as it's used in two parts of your code:

  1. To get a list of the account Ids to query
Set<Id> idList = idEmailMap.keySet();
        
String query = 'SELECT '+accountFields+' FROM Account WHERE Id =:idList';
  1. To know what the html body of the email should be for each account.

semail.setHtmlBody(idEmailMap.get(accAux.Id));


In your test, you're setting it to be a map of your user's email (value) by your user Id (key).

Map<Id,String> idEmailMap = new Map<Id,String>();
idEmailMap.put(user.Id, user.Email);

Then, when your code executes in the test context - the following query will pull no accounts

Set<Id> idList = idEmailMap.keySet(); //in your test, this is the Id of the user
        
String query = 'SELECT '+accountFields+' FROM Account WHERE Id =:idList'; //No accounts have an Id that matches your User Id

The above explains why it's not executing (there's no accounts being returned in your query) but your other parameter accIdTeamEmailMap is also empty in your test

Map<Id, List<String>> accIdTeamEmailMap = new Map<Id, List<String>>();

so when you get to this part of your code, there will be nothing to iterate over and your emails will later fail to send as there will be no toAddresses.

if( accIdTeamEmailMap.containsKey(accAux.Id)){
   for(String strAux: accIdTeamEmailMap.get(accAux.Id)){
      toAddressList.add(strAux);
   }
}

You will need to update the contents of the variables you pass to your batch in your test to reflect a real use case (with html body per test created account Ids, and email addresses per test created account Ids) so your code can properly run and you can be sure you're testing what you actually want to test.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.