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:

public class changeMultipleContactName_Test
    public static testMethod void test()

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

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


1 Answer 1



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'));

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.