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
MohiniMohini 

Please help me achieve 75% for the test class for my below class that is sending a excel attachment for account object records as email alert

class : 

global class UserReport implements Database.Batchable<SObject>, Database.AllowsCallouts, Database.Stateful {
  global  blob MyBlob;
    Set<String> nums = new Set<String>{'1%','2%','3%','4%','5%','6%','7%','8%','9%'};
   public List<String> searchstring = new List<String> {'Sales Manager','Sales User'};
    private List<String> fieldNames = new List<String> {
         'Name', 'Registry_ID_EBS__c','OwnerId', 'Owner.Email', 'Owner.IsActive'
    };
      
     global String csvContent = '';
                
    global Database.QueryLocator start(Database.BatchableContext context) {
        return Database.getQueryLocator([Select Id, Name, Registry_ID_EBS__c, OwnerId, Owner.Email, Owner.IsActive,Owner.profile.Name From Account where Owner.profile.Name IN ('Sales Manager', 'Sales User') AND Registry_ID_EBS__c like :nums ]);
    }
    
    global void execute(Database.BatchableContext context, List<Account> records) {
        Map<Id, User> owners = new Map<Id, User>();
        for (Account record : records) {
            owners.put(record.OwnerId, null);
        }
        owners.remove(null);
        owners.putAll([Select Id, Name, Email, IsActive From User Where Id IN :owners.keySet()]);
        
       /*
        for (String fieldName : fieldNames) {
            if (fieldName == 'OwnerId') {
                csvContent += '"Owner Name",';
            } else if (fieldName == 'Owner.Email') {
                csvContent += '"Owner Email",';
            } else if (fieldName == 'Owner.IsActive') {
                csvContent += '"Owner Active",';
            } else {
                csvContent += '"' + fieldName + '"' + ',';
            }
        }
        csvContent += '\n';*/
        for (Account record : records) {
            for (String fieldName : fieldNames) {
                if (fieldName == 'OwnerId') {
                    String ownerName = '';
                    if (record.OwnerId != null && owners.containsKey(record.OwnerId)) {
                        ownerName = String.valueOf(owners.get(record.OwnerId).Name).replace('"', '""');
                    }
                    csvContent += '"' + ownerName + '"' + ',';
                } else if (fieldName == 'Owner.Email') {
                    String ownerEmail = '';
                    if (record.OwnerId != null && owners.containsKey(record.OwnerId)) {
                        ownerEmail = String.valueOf(owners.get(record.OwnerId).Email).replace('"', '""');
                    }
                    csvContent += '"' + ownerEmail + '"' + ',';
                } else if (fieldName == 'Owner.IsActive') {
                    String ownerIsActive = '';
                    if (record.OwnerId != null && owners.containsKey(record.OwnerId)) {
                        ownerIsActive = String.valueOf(owners.get(record.OwnerId).IsActive).replace('"', '""');
                    }
                    csvContent += '"' + ownerIsActive + '"' + ',';
                } else {
                    Object fieldValueObj = record.get(fieldName);
                    if (fieldValueObj != null) {
                        String fieldValue = String.valueOf(fieldValueObj).replace('"', '""');
                        csvContent += '"' + fieldValue + '"' + ',';
                    } else {
                        csvContent += ',';
                    }
                }
            }
            csvContent += '\n';
           //system.debug('csvContent'+csvContent);
        }
        String Header = 'Customer Name, EBS Registry Id, Account Owner, Account Owner Email, Account Owner IsActive';
        String FinalcsvContent = Header + '\n' + csvContent ;
        MyBlob = blob.valueOf(FinalcsvContent); 
        system.debug('MyBlob1'+FinalcsvContent);

    }

   global void finish(Database.BatchableContext context) {
        system.debug('MyBlob2'+MyBlob);
    String emailAddress1 = 'mousumi.chatterjee@continuserve.com';
    Messaging.EmailFileAttachment csvAttachment = new Messaging.EmailFileAttachment();
    String myName = 'AccountList.csv';
    csvAttachment.setFileName(myName);
    csvAttachment.setBody(MyBlob);
       csvAttachment.setContentType('application/csv');
       system.debug('ss'+MyBlob);
    Messaging.SingleEmailMessage myEmail = new Messaging.SingleEmailMessage();
    String[] toAddresses = new String[]{emailAddress1};
    String subject = 'UserID and List CSV';
    myEmail.setSubject(subject);
    myEmail.setToAddresses(toAddresses);
    myEmail.setPlainTextBody('User Alias Report');
    myEmail.setHtmlBody('Hi All'+','+'</br><br/>'+ 'Please find attached the sales user detail report from Salesforce production CRM.' +'</br><br/'+'Thanks'+','+'</br>'+'Brinks Team');
   Messaging.EmailFileAttachment[] attachments = new Messaging.EmailFileAttachment[]{csvAttachment};
myEmail.setFileAttachments(attachments);

    Messaging.SendEmailResult[] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[]{myEmail});
}
}



 test class - 42%


@isTest
public class TestUserReport {
static String str = 'Name,Registry_ID_EBS__c,OwnerId,Owner.Email,Owner.IsActive \n';       

    public static String[] csvFileLines;
    public static Blob csvFileBody;

    static testmethod void testfileupload(){
        Test.startTest();       
        csvFileBody = Blob.valueOf(str);
        String csvAsString = csvFileBody.toString();
        csvFileLines = csvAsString.split('\n'); 

       UserReport result = new UserReport();
       
       // result .csvAttachment();
        Test.stopTest();
    } 

    static testmethod void testfileuploadNegative(){
        Test.startTest();       
        csvFileBody = Blob.valueOf(str);
        String csvAsString = csvFileBody.toString();
        csvFileLines = csvAsString.split('\n'); 

     UserReport result = new UserReport();
       Id batchJobId = Database.executeBatch(new UserReport(), 200);
        Test.stopTest();
    }
}
H 007H 007
Hi,
@isTest
private class TestUserReport {
    
    @testSetup
    static void setup() {
        // Create test accounts with specific fields
        List<Account> accounts = new List<Account>();
        for(Integer i=0; i<100; i++) {
            accounts.add(new Account(
                Name='Test Account ' + i,
                Registry_ID_EBS__c=i.toString() + '123',
                OwnerId=UserInfo.getUserId()
            ));
        }
        insert accounts;
    }
    
    @isTest
    static void testUserReportBatch() {
        Test.startTest();
        
        // Start the batch job
        UserReport batchJob = new UserReport();
        Database.executeBatch(batchJob);
        
        Test.stopTest();
        
        // Check if an email was sent
        List<Messaging.SingleEmailMessage> emails = [SELECT Id FROM Messaging.SingleEmailMessage];
        System.assertEquals(1, emails.size());
        
        // Check if the email attachment was generated
        List<Messaging.EmailFileAttachment> attachments = [SELECT Id, Name FROM Messaging.EmailFileAttachment];
        System.assertEquals(1, attachments.size());
        System.assertEquals('AccountList.csv', attachments[0].Name);
        
        // Check if the CSV file contains the correct headers and data
        String csvAsString = attachments[0].Body.toString();
        List<String> csvLines = csvAsString.split('\n');
        System.assertEquals('Customer Name, EBS Registry Id, Account Owner, Account Owner Email, Account Owner IsActive', csvLines[0]);
        System.assertEquals(102, csvLines.size());
        for(Integer i=1; i<101; i++) {
            System.assertEquals('Test Account ' + i + ',' + i.toString() + '123,' + UserInfo.getName() + ',' + UserInfo.getUserEmail() + ',true', csvLines[i]);
        }
    }
}

This test class first creates 100 test accounts with specific fields, then starts the UserReport batch job and checks if an email with an attachment was sent. Finally, it checks if the attachment contains the correct data.
Note that you may need to adjust the test data or the query in the start method of the UserReport class to match your requirements. Also, make sure to enable email deliverability in your org for the email to be sent successfully.
MohiniMohini
User-added image

There are 5 errors .