Skip to main content
Hi Guys,

I have the following code and want a test method to cover the for loop.Please give the test method so as to cover the for loop

Public class CreateDummyAccount{

Public static void dummyMethod(List<Account> accList){

try{

    if(accList != NULL && !accList.isEmpty()){

        List<Contact> conList = new List<Contact>();

        for(Account acc : accList){

        conList.add(new  Contact(LastName = 'Larry'))

        }

        

        insert conList;

    }

    

    }

}

}

Thanks,

Abhilash
4 answers
  1. Apr 19, 2018, 5:43 AM
    Hi Abhilash,

    To cover the for loop, you need to create the Account data setup in test class and call your dummy method.This will work for your test coverage.

    @isTest

    private class CreateDummyAccountTest

    {

    @testsetup

    static void createAccount()

    {

    List<Account> accList= new List<Account>();

    for(Integer i = 0 ; i<5 ; i++)

    {

    accList.add(new Account(Name= 'testAccountName'+i ));

    }

    insert accList;

    }

    static testMethod void test()

    {

    List<Account> accountList=[SELECT Id,Name FROM Account];

    CreateDummyAccount.dummyMethod(accountList);

    system.assert(!accountList.isEmpty());

    }

    }

     
0/9000