我正在为 Apex 批处理编写测试 class,但我只获得了 35% 的测试覆盖率

I am writing test class for Apex batch but I am getting just 35% test coverage

我正在为 Apex 批处理编写测试 class,但我只获得了 35% 的测试覆盖率。有人可以帮我吗?

主要Class

global class Emailalertbatchclass implements Database.Batchable\<sObject\>, Schedulable, Database.Stateful {

    //Variable Section
    global FINAL String strQuery;
    global List<String> errorMessages = new List<String>();
    
    global Emailalertbatchclass() { 
        this.strQuery = getBatchQuery();
    }
    
    //Returns the Query String to Batch constructor to fetch right records.
    private static String getBatchQuery() {
        String strQuery = 'Select Id, Management_Referral_Source__c,Name, Amount, StageName, LastModifiedDate, createddate, OwnerId, Owner.Email, (SELECT createddate, OldValue, NewValue FROM Histories where Field =  \'StageName\' order by createddate desc LIMIT 1) from Opportunity where StageName NOT IN (\'Closed Won - Deal Funded\', \'Closed Lost - Deal Dead\') AND Management_Referral_Source__c IN (\'Steven Tulman\', \'Rick Sekhon\', \'Cody Krieser\')  order by createddate desc'; 
        return strQuery;
        // return Database.getQueryLocator(query);
    }
    
    //Batch Start method
    global Database.QueryLocator start(Database.BatchableContext BC) {
        return Database.getQueryLocator(getBatchQuery());
    }
    
    //Batch Execute method calls findCostForWoD method
    global void execute(Database.BatchableContext BC, List<sObject> scopeList) {
        System.debug(LoggingLevel.INFO, '== scopeList size ==' + scopeList.size());
        
        Set<Integer> daysToBeCompare = new Set<Integer>{2,4,6,8,10};
        List<Opportunity> ld = (List<Opportunity>) scopeList;
        if(!ld.isEmpty()) { 
            List<Messaging.SingleEmailMessage> mailList = new List<Messaging.SingleEmailMessage>();
            for (Opportunity opp : ld){
                Date todayDate = Date.today();
                DateTime dt;
                if(!opp.Histories.isEmpty()){
                    OpportunityFieldHistory oppHistory = opp.Histories[0];
                    dt = oppHistory.createddate; 
                }
                else{
                    dt = opp.createddate;   
                }
                Date fromDate = Date.newInstance(dT.year(), dT.month(), dT.day());
                Integer numberDaysDue = fromDate.daysBetween(todayDate);      
                
                if(daysToBeCompare.contains(numberDaysDue)){
                     Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage(); 
                    String[] toAddresses = new String[] {'preeti.bhale21@gmail.com'};// {opp.Owner.Email,'','',''};
                     message.setToAddresses(toAddresses); 
                     message.setTemplateId('00XAu0000000czl');
                     message.setwhatId(opp.Id);
                     message.SaveAsActivity = false;
                     message.settargetobjectId('003Au000000FFOXIA4');
                     mailList.add(message);
                }
                
               
                
            }
            if(!mailList.isEmpty()) {
                try{
                   List<Messaging.SendEmailResult> result = Messaging.sendEmail(mailList);
                    for (Messaging.SendEmailResult mr : result) 
                        {
                            if (!mr.isSuccess()) {
                                //Do something for success
                            
                                // Operation failed, so get all errors                
                                for(Messaging.SendEmailError err : mr.getErrors()) {
                                    System.debug('The following error has occurred.');                    
                                    System.debug(err.getStatusCode() + ': ' + err.getMessage());
                                    System.debug('fields that affected this error: ' + err.getFields());
                                }
                            }
                        }
                    
               }
               
                catch (Exception ex) {
                   // System.debug(ex.getStackTraceString());
                    errorMessages.add('Unable to send email to Tech: '+ ex.getStackTraceString());
              }
            }
        }
    }  
    
    //Batch Finish method for after execution of batch work
    global void finish(Database.BatchableContext BC) { 
        AsyncApexJob aaj = [Select Id, Status, NumberOfErrors, JobItemsProcessed, MethodName, TotalJobItems, CreatedBy.Email from AsyncApexJob where Id =:BC.getJobId()];
        
        // Send an email to the Apex job's submitter notifying of job completion.
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {aaj.CreatedBy.Email};
        mail.setToAddresses(toAddresses);
        mail.setSubject('JOB Salesforce Send Notification Batch: ' + aaj.Status);
        String bodyText='Total Job Items ' + aaj.TotalJobItems + ' Number of records processed ' + aaj.JobItemsProcessed + ' with '+ aaj.NumberOfErrors + ' failures.\n';
        bodyText += 'Number of Error Messages ' + errorMessages.size() + '\n';
        bodyText += 'Error Message' + String.join(errorMessages, '\n');
        mail.setPlainTextBody(bodyText);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
    
    //Method which schedules the ProductDownloadBatch
    global void execute(SchedulableContext sc) {        
        Emailalertbatchclass snInstance = new Emailalertbatchclass();
        ID batchprocessid = Database.executeBatch(snInstance);
    }

}

测试Class

@isTest(seeAllData=false)
public class EmailAlertBatchTest {

@TestSetup
public static void makeTestData(){

    Account acc = new Account();
            acc.Name = 'Test Account' ;
            acc.Status__c = 'Hot' ;
            acc.Client_Email_Address__c = 'testaccount@xyz.com' ;
            acc.Mobile_Phone__c = '918188181' ;
            Database.insert(acc);
            
    
    Opportunity opp = new Opportunity();
            opp.Urgency__c = 'Closed Won';
            opp.Status__c = 'Closed Won';
            opp.StageName = 'Appraisal Received - Under Value';
            opp.CloseDate = date.parse('2022-03-31');
            opp.Client_Type__c = 'New';
            opp.Amount = 100000;
            opp.Main_Email__c = 'xyz@gm.com';
            opp.Current_Address__c = '111 xyz Mumbai';
            opp.SourceOfLead__c = 'Inbound Email';
            opp.Homeowner__c = 'Yes';
            opp.Residential_Lead__c = 'Yes';
            opp.Purpose_Of_Loan__c = 'Purchase';
            opp.What_are_the_best_times_to_reach_you__c ='2 am Morning';
            opp.Agent_s_Name__c = 'Steven Crowe';
            opp.AccountId=acc.Id;
            opp.Name='Test Class Opp';
         }
     
    @isTest
    
    public static void testBatchExecuteMethod()
        {
            Test.StartTest();
            Emailalertbatchclass snInstance = new Emailalertbatchclass();
            ID batchprocessid = Database.executeBatch(snInstance);
            Test.StopTest();
        }    
    
     }

insert opp; 行在哪里?没有机会,没有什么可以循环的。

并且在单元测试中,OpportunityHistory table 将为空白。您可能被迫在测试中使用 seeAllData=true 或使用 https://salesforce.stackexchange.com/q/4007/799

等技巧