[SalesForce] How to call a Batch class from test class

This is my batch class:

global class changeMultipleContactName implements Database.Batchable< sObject >
{
    global String name;
    global String n = 'Helly';
     global Database.QueryLocator start( Database.BatchableContext BC )
   {
      name = ' SELECT LastName FROM Contact WHERE LastName =:n ';  
      return Database.getQueryLocator( name );  
   }
    global void execute( Database.BatchableContext BC, List< Contact > scope )
   {
       List<Contact> con = NEW List<Contact>();
       for(Contact c:scope)
       {
           c.LastName = 'roz';
           con.add( c );
       }
       update con;
    }
     global void finish( Database.BatchableContext BC )
   {

   }
}

This is my Test class:

@isTest
public class changeMultipleContactName_Test
{
    public static testMethod void test()
    {

       Contact con= NEW Contact();
           con.LastName = 'Mahindra';
       insert con;
       test.startTest();
       changeMultipleContactName job = NEW changeMultipleContactName ( );
       job.name= 'SELECT LastName FROM Contact WHERE LastName  WHERE LastName =:n ';
       Database.executeBatch( job );
       test.stopTest();
    }
}

Here code coverage for the batch class is 41% only and the batch class is not executing.please give me solution for this.

Best Answer

Setting

con.LastName = 'Helly';

in your test will result in a record being returned and so more coverage.

However, the batchable would be better written like this:

public class ChangeContactLastName implements
        Database.Batchable<sObject>, Database.Stateful {

    private String fromLastName;
    private String toLastName;

    public ChangeContactLastName(String fromLastName, String toLastName) {
        this.fromLastName = fromLastName;
        this.toLastName = toLastName;
    }

    public Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator([
                select Id
                from Contact
                where LastName = :fromLastName
                ]);  
    }

    public void execute(Database.BatchableContext bc, List<Contact> scope) {
        for (Contact c: scope) c.LastName = toLastName;
        update scope;
    }

    public void finish(Database.BatchableContext bc) {
    }
}

so that it could be called like this:

Database.executeBatch(new ChangeContactLastName('Helly', 'roz'));
Related Topic