0

I'm getting the following exception while executing batch class from text class

System.UnexpectedException: No more than one executeBatch can be called from within a test method. Please make sure the iterable returned from your start method matches the batch size, resulting in one executeBatch invocation.

@isTest(seeAllData=FALSE)
public class NorthDivisionUsersBatchTest 
{
    public static testMethod void testNorthDivisionUsersBatch() 
    {
        Profile p = [SELECT Id FROM Profile WHERE Name='Standard User']; 
        User u = new User(Alias = 'standt', Email='[email protected]', 
            EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
            LocaleSidKey='en_US', ProfileId = p.Id, Division='NORTH DIVISION',
            TimeZoneSidKey='America/Los_Angeles', UserName='[email protected]'); insert u;
        Test.startTest();

        System.runAs(u) {
            // The following code runs as user 'u' 
            Database.executeBatch(new NorthDivisionUsersBatch(), 200);
        }
        Test.stopTest();
    }
}

I'm not able to understand what's wrong in my code, please help me to understand it. Following is the main class

    public class NorthDivisionUsersBatch implements Database.Batchable<sObject> {

  public Database.QueryLocator start(Database.BatchableContext bc) {
     String currentDivision = 'NORTH DIVISION';
     String query = 'SELECT Id, FirstName, LastName, Name, Title, LastLoginDate,Username,Division,CompanyName,Department,License_Type__c  FROM User WHERE isActive = true AND Division = \'NORTH DIVISION\'' ;
    return Database.getQueryLocator(query);
  }

  public void execute(Database.BatchableContext bc, List<User> userList){
    String header = 'First Name, Last Name,Last login date,Days Since Last Login, Title, Division, Company, Department, License Type, Username\n';
    String finalstr = header;
    Integer southDivision = 0;
    Integer northDivision = 0;
    Integer westDivision = 0;
    Integer interiorDivision = 0;
      for(User u : userList){

           Long days = 0;
       Date lastLogin;
           DateTime lt = u.LastLoginDate;

           if(u.LastLoginDate != null || Test.isRunningTest()){
        Long milliseconds = DateTime.now().getTime() - (u.LastLoginDate).getTime();
                Long seconds = milliseconds / 1000;
                Long minutes = seconds / 60;
                Long hours = minutes / 60;
                days = hours / 24;

        //lastLogin = date.newinstance(lt.year(), lt.month(), lt.day());
        //lt = lt.format('MMMMM dd, yyyy');
           }
           if(days > 30 || Test.isRunningTest()){
         String records = u.FirstName+','+u.LastName+',';


               //if(u.Division.equals('NORTH DIVISION')){
                //   Northdivision = u.Division.size();
               //}else if(u.Division == 'SOUTH DIVISION'){
               //    Southdivision = u.Division.size();
              // }else if(u.Division == 'WEST DIVISION'){
               //    Westdivision = u.Division.size();
              // }

         if(lt != null || Test.isRunningTest()){
           records += lt.format('MMMMM dd yyyy')+',';
           records += days+',';
         }else{
           records += ''+',';
           records += ''+',';
         }

         if(u.Title != null || Test.isRunningTest()){
           records += u.Title+',';
         }else{
           records += ''+',';
         }

         if(u.Division != null){
           records += u.Division+',';
                /*if(u.Division =='NORTH DIVISION'){
                   northDivision = northDivision+1;
                }else if(u.Division == 'SOUTH DIVISION'){
                   southDivision = southDivision+1;
                }else if(u.Division == 'WEST DIVISION'){
                   westDivision = westDivision+1;
                }else if(u.Division == 'INTERIOR DIVISION'){
                    interiorDivision = interiorDivision+1;
                }*/

         }else{
           records += ''+',';
         }

         if(u.CompanyName != null){
           records += u.CompanyName+',';
         }else{
           records += ''+',';
         }

         if(u.Department != null){
           records += u.Department+',';
         }else{
           records += ''+',';
         }

         if(u.License_Type__c != null){
          records += u.License_Type__c+',';
         }else{
           records += ''+',';
         }

         if(u.UserName != null){
           records += u.UserName+',';
         }else{
           records += ''+',';
         }
         records +='\n';

         finalstr = finalstr+records;

       }

     }

    Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
    blob excel = blob.valueOf(finalstr);
    attach.setBody(excel);
    attach.setFileName('SFuserdetails.csv');
        String subject = 'SalesForce Login activity';
    //String body = 'Users who are not logged in since last 30 days';
        String body = 'Please find attached file';

    string[] address = new string[]{'[email protected]'}; 

    Messaging.singleEmailMessage Emailwithattch = new Messaging.singleEmailMessage();

    Emailwithattch.setSubject(subject);

    Emailwithattch.setToaddresses(address);

    Emailwithattch.setHtmlBody(body);



    Emailwithattch.setFileAttachments(new Messaging.EmailFileAttachment[]{attach});

    // Sends the email

    Messaging.SendEmailResult [] r =

    Messaging.sendEmail(new Messaging.SingleEmailMessage[] {Emailwithattch});
  }    

  public void finish(Database.BatchableContext bc){
     // execute any post-processing operations
  }    
}

1 Answer 1

2

This limitation of batchables in tests is "by design" in the platform.

As you are querying actual User records, a way to ensure there is only one batch is to append a SOQL limit in the start method when running the test:

String query = 'SELECT Id, FirstName, LastName, Name, Title, LastLoginDate,Username,Division,CompanyName,Department,License_Type__c  FROM User WHERE isActive = true AND Division = \'NORTH DIVISION\'' ;
if (Test.isRunningTest()) query += ' limit 200';
1
  • that worked for me need to limit the users from test class Commented Jun 9, 2019 at 15:39

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .