You need to sign in to do that
Don't have an account?

test method to cover for loop
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
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
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.
The for loop is not covered because there is no data in your account list, the program just bypassed your code.
So you need to add some fake data before the loop, the easiest way is to add the below line before your if statement.
accList.add(new Account(Name= 'TestAcc'));
Best regards,
Hank
If you are using the trigger on an Account. You can not write this 'CreateDummyAccount.dummyMethod(accList);'
You can only insert Dummy Data and you can write 'System.debug()' for checking method data.
//Apex Class//
Public class CreateDummyAccount{
Public static void dummyMethod(List<Account> accList){
System.debug('Account List--->'+accList);
try{
if(accList != NULL && !accList.isEmpty()){
List<Contact> conList = new List<Contact>();
for(Account acc : accList){
System.debug('Account is -->'+acc);
conList.add(new Contact(LastName = 'Larry'));
}
insert conList;
}
}catch(DMLException e){
System.debug('There is error'+e.getMessage());
}
}
}
//Test Class //
@IsTest
private class CreateDummyAccount_Test {
@IsTest
static void method1(){
List<Account> accList = new List<Account>();
for(Integer i =0;i<2;i++){
Account ac = new Account();
ac.Name = 'AccountName'+i;
accList.add(ac);
}
insert accList;
Test.startTest();
CreateDummyAccount.dummyMethod(accList);
Test.stopTest();
}
}
Please mark it as best if you find it helpful.
Thank You
Ajay Dubedi