• jimmy parker
  • NEWBIE
  • 0 Points
  • Member since 2021

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 1
    Replies
Hi

i have a batch class and i have written a test class for that batch class. it is working fine. But i don't know how to do negative testing for that batch class.

Batch class:= 

public class MyBatchable implements Database.Batchable<SObject> {

    public Database.QueryLocator start(Database.BatchableContext context) {
        return Database.getQueryLocator([select Id from Account where name like 'acc%' order by Name]);
    }

    public void execute(Database.BatchableContext context, List<Account> scope) {
        try{
        Account[] updates = new Account[] {};
        for (AggregateResult ar : [select AccountId a, count(Id) c from Contact where AccountId in :scope and active__c=true group by AccountId])
        {
            updates.add(new Account(Id = (Id) ar.get('a'), No_of_Active_Contacts__c = (Decimal) ar.get('c')));
        }
        update updates;
    }
        catch(Exception e) {
        System.debug('An exception occurred: ' + e.getMessage());
}
    }

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


Test class for batch class:=

@isTest
public class MyBatchableTest {
    static testMethod void testme(){
        Account Acc = new Account();                                             
        Acc.Name='acc1';
        insert Acc;
        
        contact con= new contact();
        con.LastName = 'test';
        con.AccountId = Acc.Id;
        con.active__c = true;
        
        insert con;
        test.startTest();
        MyBatchable ba= new MyBatchable();
        Id jobid= Database.executeBatch(ba,5);
        test.stopTest();
    }
}

Thanks and Regards
Sachin