function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
SFDC ROCKSFDC ROCK 

Apex code Test class

How to write test class for below class

 global void execute(Database.BatchableContext bc, List<opportunity> scope){
 List<opportunity>  ls=new list<opportunity>();
  Map<Id,opportunity> update = new Map<Id,opportunity>();
  for(opportunity oppty:scope){
 if(oppty.abc=='P' && oppty.abc!='M' 
                           && oppty.createdby.profile.Name=='Custom: TCT'){
                            oppty.abc='M';
                             //Updated below opptyListUpdate List to update Map as to avoid duplicate values
                             update.put(oppty.Id,oppty);
                             ls.add(oppty);
                             break;
Ajay K DubediAjay K Dubedi
Hi Subodh,

I have seen your Batch code and I am not able to understand what 'abc' is, that you use in your code.
So I created an 'abc__c' field on Opportunity of Picklist type and also created start and finish methods.

Batch Class:
 
global class Test_Class implements Database.Batchable<sObject>
{
    global Database.QueryLocator start(Database.BatchableContext BC)
    {
        String query = 'SELECT Id,abc__c,CloseDate,StageName,Name FROM Opportunity';
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext bc, List<opportunity> scope)
    {
        List<opportunity>  ls=new list<opportunity>();
        Map<Id,opportunity> update_Map = new Map<Id,opportunity>();
        for(opportunity oppty:scope)
        {
            if(oppty.abc__c=='P' && oppty.abc__c!='M' 
               && oppty.createdby.profile.Name=='Custom: TCT')
            {
                oppty.abc__c='M';
                //Updated below opptyListUpdate List to update_Map Map as to avoid duplicate values
                update_Map.put(oppty.Id,oppty);
                ls.add(oppty);
                break;
            }
        }
    }
    global void finish(Database.BatchableContext BC) 
    {
    }
}

Test Class:

@isTest
public class Class_Test 
{
    public TestMethod static void Class_Test_Method()
    {
        List<Opportunity> op_List = New List<Opportunity>();
        Opportunity op = new Opportunity();
        op.abc__c = 'P';
        op.name='Hello';
        op.CloseDate=date.today();
        op.StageName='Prospecting';
        op_List.add(op);
        Test.startTest();
        Database.SaveResult []str = Database.insert(op_List,false);
        system.assertEquals(True, str[0].isSuccess());
        Test_Class abcd = New Test_Class();
        Database.executeBatch(abcd);
        Test.stopTest();
    }
}

*It Shows 100% code coverage for this batch class

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Ajay Dubedi
www.ajaydubedi.com