A fresher question.
As per the Apex guide online,
the following is a test factory class
@isTest
public class TestDataFactory {
public static void createTestRecords(Integer numAccts, Integer numContactsPerAcct) {
List<Account> accts = new List<Account>();
for(Integer i=0;i<numAccts;i++) {
Account a = new Account(Name='TestAccount' + i);
accts.add(a);
}
insert accts;
for (Integer j=0;j<numAccts;j++) {
Account acct = accts[j];
List<Contact> cons = new List<Contact>();
// For each account just inserted, add contacts for (Integer k=numContactsPerAcct*j;k<numContactsPerAcct*(j+1);k++) {
cons.add(new Contact(firstname='Test'+k,lastname='Test'+k,AccountId=acct.Id));
}
insert cons;
}
}
}
This test factory class from above has one sole purpose of creating generic test data and can be called from other test classes like below.
@isTest
private class MyTestClass {
static testmethod void test1() {
TestDataFactory.createTestRecords(5,3); ///QUESTION
// Run some tests
}
}
My question is at "QUESTION" indicated line above.
The "TestDataFactory.createTestRecords()" does not return any data as indicated by "void" in its method definition.
Then how "MyTestClass.test1()" will be able to obtain and test the data generated by the utility class ?
Can someone throw light on this ?
Best Answer
The
createTestRecords
method commits data to the database usinginsert
.The records that have been inserted can be retrieved using SOQL:
Personally I prefer to return the records I create in these types of methods as it means I have access to the inserted records (and their
Id
) without needing the query the database: