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
sruthi26sruthi26 

My test class shows only 19% code coverage for a batch class. How can I improve it.

My batch class:
global class DeactivateOnTrackUserBatch implements Database.Batchable<sObject>,Database.AllowsCallouts {
public String query = 'SELECT Id, Enable_Ontrack__c ,CreatedOntackUser__c , Username  FROM User where Enable_Ontrack__c = \'no\' AND CreatedOntackUser__c = True '; 
 global Database.QueryLocator start(Database.BatchableContext BC) {
    return Database.getQueryLocator(query);
 }
global void execute(Database.BatchableContext BC, List<User> UserRecords) {  
 ontrackworkflowComWebservicesUser.OTWSUserServiceSoap s1 = new ontrackworkflowComWebservicesUser.OTWSUserServiceSoap();
 String result;
 system.debug('user records' + UserRecords );
   for (user u : UserRecords ) {
 ontrackworkflowComWebservicesAuth.OTWSAuthenticationServiceSoap sp = new ontrackworkflowComWebservicesAuth.OTWSAuthenticationServiceSoap();
  if(!Test.isRunningTest()) {
         string resulttoken = sp.Login('sfdcOnTrackAPI','ontrack_sfdc');
         system.debug(resulttoken);
         JSONParser parser = JSON.createParser(resulttoken);
         system.debug(parser);
         string ticket;
         while (parser.nextToken() != null) 
         {
           if(parser.getCurrentName() == 'Ticket') 
           {
             ticket = parser.getText();                                 
             system.debug(parser.getText());
           }  
         }        
 //system.debug('user id' + u.Id);
  //u.Id = UserInfo.getUserId();
  result = s1.DeactivateUserSFDC(ticket, u.Id);
         System.Debug('result' + result);
         if (result.indexOf('Fail') == -1){
         u.CreatedOntackUser__c = False;
         Update u;
         System.Debug('result testing' + result); 
          }
        }
}
}
    global void finish(Database.BatchableContext BC){    
    }
}


My Test Class:

@isTest
private class DeactivateOnTrackUserBatch_Test {
    public static testMethod void DeactivateOnTrackUserBatch_Test() {
    User objUser = [select id from user where  id=:userinfo.getuserid()];
    System.runAs(objUser){   
    Test.startTest();    
    DeactivateOnTrackUserBatch d = new  DeactivateOnTrackUserBatch();    
    String deactID = System.scheduleBatch(d, 'job example10', 1); 
                Database.executeBatch(d, 200);
               // d.execute(null,null);  
    Test.stopTest();
    }  }
}
Best Answer chosen by sruthi26
Amit Chaudhary 8Amit Chaudhary 8
You need to create the test data according to your Query in Batch job.
@isTest
private class DeactivateOnTrackUserBatch_Test 
{
    public static testMethod void DeactivateOnTrackUserBatch_Test() 
	{
		Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator']; 
		
		User objUser = new User(	Alias = 'standt', Email='standarduse1r@testorg.com', 
							EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
							LocaleSidKey='en_US', ProfileId = p.Id, 
							Enable_Ontrack__c ='no',
							CreatedOntackUser__c = true ,
							TimeZoneSidKey='America/Los_Angeles', UserName='standarduse1r@testorg.com'
			);
			
		insert objUser;
		
		Test.startTest();    
				DeactivateOnTrackUserBatch d = new  DeactivateOnTrackUserBatch();    
				String deactID = System.scheduleBatch(d, 'job example10', 1); 
							Database.executeBatch(d, 200);
						   // d.execute(null,null);  
		Test.stopTest();
	}
}

NOTE:- your are using !Test.isRunningTest() in your test class means that code will never execute in test class. So you need to remove that and need to use mock Test class.
1) https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_http_testing_httpcalloutmock.htm
2) https://developer.salesforce.com/blogs/developer-relations/2013/03/testing-apex-callouts-using-httpcalloutmock.html

Let us know if this will help you

All Answers

devcg15devcg15
Hi sruthi,

When testing your batch Apex, you can test only one execution of the execute method.Use theexecuteBatch method, it ensures that you aren’t running into governor limits. The executeBatch method starts an asynchronous process. This means that when you test batch Apex, you must make certain that the batch job is finished before testing against the results. Use the Test methods startTest and stopTest around theexecuteBatch method to ensure that it finishes before continuing your test.

Thanks 
Indranil 
Amit Chaudhary 8Amit Chaudhary 8
You need to create the test data according to your Query in Batch job.
@isTest
private class DeactivateOnTrackUserBatch_Test 
{
    public static testMethod void DeactivateOnTrackUserBatch_Test() 
	{
		Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator']; 
		
		User objUser = new User(	Alias = 'standt', Email='standarduse1r@testorg.com', 
							EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
							LocaleSidKey='en_US', ProfileId = p.Id, 
							Enable_Ontrack__c ='no',
							CreatedOntackUser__c = true ,
							TimeZoneSidKey='America/Los_Angeles', UserName='standarduse1r@testorg.com'
			);
			
		insert objUser;
		
		Test.startTest();    
				DeactivateOnTrackUserBatch d = new  DeactivateOnTrackUserBatch();    
				String deactID = System.scheduleBatch(d, 'job example10', 1); 
							Database.executeBatch(d, 200);
						   // d.execute(null,null);  
		Test.stopTest();
	}
}

NOTE:- your are using !Test.isRunningTest() in your test class means that code will never execute in test class. So you need to remove that and need to use mock Test class.
1) https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_http_testing_httpcalloutmock.htm
2) https://developer.salesforce.com/blogs/developer-relations/2013/03/testing-apex-callouts-using-httpcalloutmock.html

Let us know if this will help you
This was selected as the best answer
sruthi26sruthi26
Thanks Amit. That worked!!