+ Start a Discussion

Code coverage

Hi All,

Here is the batch apex for capturing system generated lastlogin date into a custom field.

1.Batch Apex

global class CaptureLastLoginDate implements Database.Batchable<sObject>{

//This is the query that is passed to the execute method. .

String ids = UserInfo.getUserId();
String query = 'SELECT id, LastLoginDate,LastLoginDate__c FROM User ';

global database.queryLocator start(Database.BatchableContext BC) {
return database.getQueryLocator(query);
//close start method
global void execute(Database.BatchableContext BC, List<sObject> scope){
    List<Schema.User> u = new List<Schema.User> ();
    for(sObject s: Scope){
        Schema.User inv = (Schema.User)s;
        inv.LastLoginDate__c= inv.LastLoginDate;
    update u;


    global void finish(Database.BatchableContext sc){


2.Scheduled batch

global class scheduledMerge1 implements Schedulable {
   global void execute(SchedulableContext SC) {
       CaptureLastLoginDate M = new  CaptureLastLoginDate(); 
      scheduledMerge1 pa= new scheduledMerge1();
String cronStr = '0 0 * * * ? *';
 System.schedule('scheduledMerge1 Job', cronStr, pa);


4.Test Class for Batch APex

 Private class LastLogintest
 static testMethod void CaptureLastLoginDate()
String ids = UserInfo.getUserId();

    // Making the assumption that at least one user will match this. Better to assign to list and check that has at least one record.
    Schema.User testUser = new Schema.User();
    testUser=[SELECT id, LastLoginDate,LastLoginDate__c FROM User limit 1];
    // Set it to anything other than LastLoginDate so we can tell it has changed.
   //insert testUser;

    CaptureLastLoginDate captureBatch = new CaptureLastLoginDate();
    // Modify the query here so we only get our one testing user of interest
    //captureBatch.query = 'SELECT id, LastLoginDate,LastLoginDate__c FROM User where Id =:testUser.Id';
    ID batchprocessid = Database.executeBatch(captureBatch,1);

    Schema.User afterBatchUser = [Select Id, LastLoginDate, LastLoginDate__c from User where Id =:testUser.Id limit 1];
    System.AssertEquals(afterBatchUser.LastLoginDate, testUser.LastLoginDate__c);

5.Test Class for scheduled apex

Private class Capturetest{
static testMethod void scheduledMerge()

scheduledMerge pa= new scheduledMerge();
String cronStr = '0 0 * * * ? *';



Note:There were no errors in the code. test class for scheduled apex was running fine.but the test class for batch apex failed.Suggest


Hi ,


What is the failure message in Batch's test class.?



The test class for batch apex failed.