+ Start a Discussion
ranga babu vangalapudi 2ranga babu vangalapudi 2 

my test class in not covering the code inside for loop

This is my Schedule class:

global class OutletExporter implements System.Schedulable {
    global void execute(SchedulableContext sc) {
        String today = Datetime.now().AddDays(-1).format('dd-MM-yyyy');
        List<Account> accList = [Select RPC__c,Cluster__c,TL_Territory_Name__c,Team_Lead_Employee_ID__c,TSE_Name__c,TSE_ID__c,TSE_Code__r.Outlet_Count__c  from Account where CreatedDate =Yesterday LIMIT 50000];
        //List<Account> latestModiaccList = [Select Id,Name, AccountNumber, Industry, CreatedDate,LastModifiedDate,Phone from Account where LastModifiedDate=TODAY AND CreatedDate !=TODAY];
        
        String header = 'Accounts inserted Today \r\n\n'+ 'RPC, Cluster, TLTerritory Name, TL EMP ID,TSE Territory Name,TSE EMP ID,Outlet Count \r\n';
        //String header1 ='\r\n\bAccounts Modified Today\b\r\n'+ '\bId, Name, Account Number, Industry,Phone\b\r\n';
        String generatedCSVFile = header+'';
        List<String> queryFields = new List<String>{'RPC__c','Cluster__c','TL_Territory_Name__c','Team_Lead_Employee_ID__c','TSE_Name__c','TSE_ID__c','Outlet Count'};
        String fileRow = '';
        system.debug('My Account List:'+accList);
        for(Account a: accList){
        fileRow = '';
        fileRow = fileRow +','+ a.RPC__c;
        fileRow = fileRow +','+ a.Cluster__c;
        fileRow = fileRow +','+ a.TL_Territory_Name__c;
        fileRow = fileRow +','+ a.Team_Lead_Employee_ID__c;
        fileRow = fileRow +','+ a.TSE_Name__c;
        fileRow = fileRow +','+ a.TSE_ID__c;
           fileRow = fileRow +','+ a.TSE_Code__r.Outlet_Count__c;
        fileRow = fileRow.replaceFirst(',','');
        generatedCSVFile = generatedCSVFile + fileRow + '\n';
        }
        Messaging.EmailFileAttachment csvAttachment = new Messaging.EmailFileAttachment();
        Blob csvBlob = blob.valueOf(generatedCSVFile);
        String csvName = 'Outlets inserted and modified on '+today+'.csv';
        csvAttachment.setFileName(csvName);
        csvAttachment.setBody(csvBlob);
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[]{'ranga.vangalapudi@diageo.com','jayalakshmi.t@ivymobility.com','jennifer.b@ivymobility.com','Pradeep.Shiggavi@diageo.com','Nithyananda.Alva@diageo.com','Rajat.Yadav@diageo.com'};
        String subject = 'Outlets inserted and modified on '+today+'';
        email.setSubject(subject);
        email.setToAddresses(toAddresses);
        email.setPlainTextBody('Outlets inserted and modified on '+today+'');
        email.setFileAttachments(new Messaging.EmailFileAttachment[]{csvAttachment});
        Messaging.SendEmailResult[] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[]{email});
       }
}

This is the my test class
@isTest
public class OutletExporterTest {
     
    static testmethod void testoutlets(){        
       Id RecordTypeId = Schema.SObjectType.Masters__c.getRecordTypeInfosByName().get('Cluster').getRecordTypeId();
        Masters__c master = New Masters__c();
        master.Cluster_Name__c='RPCSCL004';
        master.RecordTypeid=RecordTypeId;
        insert master;
        TL_Master__c tl= new TL_Master__c();
        tl.Name='APTL001';
        tl.TL_Territory_Name__c='CENTRAL COASTAL';
        tl.Cluster__c=master.id;
        insert tl;
        
        TSE_Master__c oldTse1 = new TSE_Master__c();
        oldTse1.Name = 'APTS001';
        oldTse1.TSE_Territory_Name__c = 'AMALAPURAM';
        oldTse1.TL_Code__c=tl.id;
        insert oldTse1;
        
        Beat_TSE_Mapping__c NewBte = new Beat_TSE_Mapping__c();
        NewBte.Beat_Name__c = 'Beat_1';
        NewBte.Name = 'KABT0564';
        NewBte.TSE_Code__c = oldTse1.id;
        insert NewBte;
        
        
        Account acc = new Account();
        acc.name = 'test name';
        //acc.RPC__c = 'RPC-N' ;
        acc.Active__c = 'Waiting Approval';
        acc.Pincode__c = '560068';
        // acc.Beat_Name__c = 'testBeat';
        acc.Town__c = 'testTown';
        acc.Outlet_License_Name__c = 'testOl';
        acc.Address__c = 'testadd';
        acc.Stock_List__c = 'Tier 1';
        acc.Channel_type__c = 'Off';
        acc.Micro_channel__c = 'Browsable PTO';
        acc.Perfect_Outlet__c = 'Yes';
        acc.Contract_type__c = 'Open';
        //acc.TL_Territory_Name__c = 'Gurgaon 3';
        //acc.RH_Territory_Name__c = 'Haryana 3';
        //acc.Cluster__c = 'Haryana 1' ;
        acc.District__c = 'Gurgaon 3';
        acc.Goegraphy_state__c = 'Haryana';
        acc.Market_Type__c='Bond Market';
        acc.MSL_Town_Tier__c='Uncovered';
        acc.Beat_Code__c= NewBte.Id;
        acc.Cluster_Code__c=master.Id;
        acc.TSE_Code__c=oldTse1.id;
        acc.TL_Code__c=tl.Id;
        acc.Outlet_Type__c='D';
        acc.Group_Outlet__c='No';
        insert acc ; 
        Account NewAcc = new Account();
        NewAcc.id = acc.id;
        NewAcc.Beat_Code__c = NewBte.ID;
        //  NewAcc.Beat_Name__c = NewBte.Beat_Name__c ; 
        //NewAcc.TSE_Code__c = oldTse3.id;
        // NewAcc.TSE_ID__c = NewBte.TSE_ID__c;
        // NewAcc.TSE_Name__c = NewBte.TSE_Name__c;
        NewAcc.District__c = 'Test District1';
        NewAcc.Town__c = 'Test Town1';
        NewAcc.Name = 'Test name1';
        update NewAcc;
            Test.startTest();
            OutletExporter  objTest = new OutletExporter();
            String sch = '0 0 7 ? * * *';
            system.schedule('Test Schdule', sch, objTest); 
            Test.stopTest();
    }
}

Please help me on this?
Best Answer chosen by ranga babu vangalapudi 2
Akshay_DhimanAkshay_Dhiman
Hi Ranga,
I can see that you are creating a record for Account which of today's date that's why your for loop is not covering inside the Class 
Use this way to create backdate data record in Test class this is going to cover your for a loop  --
Example --
@isTest
public class AccountBackDateTestClass {
    @isTest static void TestValue()
    {
        Account acc = new Account();
        acc.Name = 'Test';
        insert acc;
       Datetime yesterday = Datetime.now().addDays(-1);
Test.setCreatedDate(acc.Id, yesterday);
        AccountBackDateExample.showTest();
    }

}


If found this helpful mark it as best so that it helps others in solving the same.


    Thanks 
    Akshay

All Answers

Akshay_DhimanAkshay_Dhiman
Hi Ranga,
I can see that you are creating a record for Account which of today's date that's why your for loop is not covering inside the Class 
Use this way to create backdate data record in Test class this is going to cover your for a loop  --
Example --
@isTest
public class AccountBackDateTestClass {
    @isTest static void TestValue()
    {
        Account acc = new Account();
        acc.Name = 'Test';
        insert acc;
       Datetime yesterday = Datetime.now().addDays(-1);
Test.setCreatedDate(acc.Id, yesterday);
        AccountBackDateExample.showTest();
    }

}


If found this helpful mark it as best so that it helps others in solving the same.


    Thanks 
    Akshay
This was selected as the best answer
ranga babu vangalapudi 2ranga babu vangalapudi 2
Hi Akshay,
Thanks for your quick response.

what is "AccountBackDateExample" is it a schedulable class or anything else

Thanks,
Ranga
Akshay_DhimanAkshay_Dhiman
Hi Ranga,
Its a Normal (Apex class) Name -- AccountBackDateExample and its method -- showTest which we 
want to cover through this test class above.
Refer to this example also 

That will make you more clear --
 
@isTest 
private class SetCreatedDateTest {
    static testMethod void testSetCreatedDate() {
        Account a = new Account(name='myAccount');
        insert a;
        Test.setCreatedDate(a.Id, DateTime.newInstance(2012,12,12));
        Test.startTest();
        Account myAccount = [SELECT Id, Name, CreatedDate FROM Account 
                             WHERE Name ='myAccount' limit 1];
        System.assertEquals(myAccount.CreatedDate, DateTime.newInstance(2012,12,12));
        Test.stopTest();
    }
}


Thanks 
Akshay
ranga babu vangalapudi 2ranga babu vangalapudi 2
Hi Akshay,

Thanks for your help

Ranga