I was writing allot of test code to create SObjects and all the necessary fields. There are some problems when writing test code when specifying all the necessary fields.
Some of the things to consider when creating test fields is required fields and pre-populating lookups. Let us look at some examples:
Let’s start of creating a Account in a Test Class:
Account newAccount = new Account(Name='This is a Test Account');
Now we create the Contact associated to that Account:
Contact newContact = new Contact(AccountId=newAccount.Id);
but Contact has more required fields and will fail if I call the:
Let’s take it a bit further and create an Opportunity and select the newAccount.
Opportunity newOpportunity = new Opportunity(AccountId=newAccount.Id);
the same story for opportunity is we need more required fields to be completed, and do we always know the required fields?No for some unknown Salesforce orgs this may be a problem.
Let’s see how we can solve the problem of required fields and lookup during sObject creation:
Contact c = (Contact)SmartFactory.createSObject('Contact', true);
The second argument (true) toggles the cascade option, which populates any lookup fields on the object with their own newly created objects. It’s a powerful way to create hierarchies of test data quickly and easily so you can focus on writing test and implementation logic.
Now we can create an Opportunity without specifying an Account or Contact:
Opportunity o = (Opportunity)SmartFactory.createSObject('Opportunity', true);
This will create, a Account, Contact and Opportunity for you in one line.
SmartFactory uses the describe metadata to populate all fields with data of the right type. It currently handles string and lookup fields. For lookup fields, it creates an appropriate object and then uses that object’s ID.