I'm having issues with creating a pretty simple test Utility Class. I want to create two records: an account and a related child contact. The error I see in the developer console is:
Variable does not exist: a.ID
My code, based on the Salesforce Apex Workbook, is as follows. I've played around with various things, but it's not working. Where am I going wrong? Thanks in advance.
@isTest
public class AccountSaveTestSuite {
public static Account createOneAccount(){
Account testAccount = createAcct('ABC Computing inc.');
Contact testContact = createContact();
return testAccount;
}
// Helper methods //
//
private static Account createAcct(string accountName) {
Account a = new Account(
Name=accountName);
insert a;
return a;
}
private static Contact createContact(){
Contact c = new Contact (
FirstName = 'Jane'
, LastName = 'Smith'
, Account = a.ID); // *** Error is here ***
insert c;
return c;
}
}
Best Answer
Curly brackets are used to indicate scope in Apex (and other C-like languages). It could be the scope of your class, method, or a separate scope that you've defined within one of those.
You can access variables that have been declared in your current scope and parent scope(s), but not those defined in child scopes or parallel scopes.
In addition to this you cannot access instance variables from a static scope without an object reference.
In your case you are trying to access a variable
a
that has been defined in a parallel scope (thecreateAcct
method) to your current scope (thecreateContact
method).This can be resolved be passing a reference to your
Account
object to youcreateContact
method:Scope Examples
Instance Variables
Static Variables
Parallel Scopes
Mixing Instance & Static Variables