You need to sign in to do that
Don't have an account?
dmcheng
List popluation not working in a for loop
Hello. I'm trying to populate a list with some dummy records so I can do some unit testing. However, when I do a for loop, the list remains null and the assertion fails. I've tried two different assignment techniques but neither works. If I get rid of either for loop and just put in a line j = 0, then the list is populated. I can't figure out what I'm doing wrong here.
Thanks
David
Thanks
David
Code:
public class Util { static testmethod void testAllTriggers() { Integer i, j; //Set up a contact and payments for testing. Contact person = new Contact(FirstName = 'John', LastName = 'Qwertyuiop'); insert person; Id contactID = [select id from Contact where LastName = 'Qwertyuiop'].Id; Membership_Payment__c[] payments = new Membership_Payment__c[23]; //THIS LOOP FAILS TO POPULATE // for (j = 0; j == 22; j++) { // payments[j] = new Membership_Payment__c(Contact__c = ContactID, Name = (2010 + j).format(), // Posted_Date__c = Date.newInstance(2010 + j, 1, 2), Amount__c = 20); // } //THIS LOOP ALSO FAILS TO POPULATE // for (j = 0; j == 22; j++) { // payments.add(new Membership_Payment__c(Contact__c = ContactID, Name = (2010 + j).format(), // Posted_Date__c = Date.newInstance(2010 + j, 1, 2), Amount__c = 20)); // } system.assertEquals(date.newInstance(2010, 1, 2), payments.get(0).Posted_Date__c);
try replacing 'j ==22' with 'j <= 22'
No problem, the for loop will execute until the condition is no longer true. As you had j == 22 this was never true and so would never execute.
For loops continue to loop until the boolean evaluates to FALSE. In other words:
for (j = 0; j == 22; j++) {}
j = 0;
does j equal 22? No. Returns false.
Close loop.
for (j = 0; j <= 22; j++) {}
j = 0;
is j less than or equal to 22? Yes. Returns true.
Do what's in the brackets.
Increase j by 1. (j now equals 1)
is j less than or equal to 22? Yes. Returns true.
Do what's in the brackets.
Increase j by 1. (j now equals 2)
is j less than or equal to 22? Yes. Returns true.
Do what's in the brackets.
Increase j by 1. (j now equals 3)
etc. etc.
Cheers,
Jody