+ Start a Discussion

Can you please help me with the test class syntax to cover this for loop?

User-added image
ANUTEJANUTEJ (Salesforce Developers) 
Hi Rahul,

You will need to have records that satisfy the mentioned condition to make sure the snippet after the conditional statement also gets covered.

Let me know if it helps you and close your query by marking it as the best answer so that it can help others in the future.  

Hi Anutej, Thanks for your Reply. How can I add the Records? Shaould I add it in Test class query?
Prafull Jain22Prafull Jain22
Use the testsetup anotation method that will run firstly in test class and applied to each testmethod/@isTest anotation method
@testSetup static void setup() {
        // Create common test accounts
         List<Account> testAccts = new List<Account>();
        for(Integer i=0;i<2;i++) {
            testAccts.add(new Account(Name = 'TestAcct'+i));
        insert testAccts;
        List<Address_By_BP__c> testAddress = new List<Address_By_BP__c>();
        for(Accounts a:testAccts) {
        insert testAddress;
         List<Case> testCase = new List<Case>();
        for(Accounts a:testAccts) {
            testCase.add(new Case(Subject=a.Id+ 'sa',AccountId=a.Id));
        insert testCase;
        List<ServiceForm__c> testServForm = new List<ServiceForm__c>();
        for(Case c:testCase) {
            testServForm.add(Name='Test Ser',Case__c=c.id);
        insert testServForm;
    @isTest static void testMethod1() {
    List<ServiceForm__c> ServFormLs=[Select Id from ServiceForm__c Where Name='Test Ser'];
    List<Address_By_BP__c> AddressBPLs=[Select Id from Address_By_BP__c Where Address_Code__c='23'];
    //Add your snap code for further condition
    //User either System.assert() or System.assertEquals()
    //User Test.startTest() and Test.stopTest() for performing unit test.

Please refer below link

If you find this is helpful please marks it as the best answer so that it can help others in the future.