2

The following SOQL in test classes gives a list of contacts but it doesn't lists any related account fields.

List<Contact> contacts = new List<Contact>([Select Id, Email, AccountId, Account.Name From Contact]);

If I use System.debug('contacts: ' + contacts); - this just gives me the Id, Email and AccountId but no Account.name which is something like: (Contact:{[email protected], AccountId=00124000007HfzOAAS, Id=0032400000593u8AAA}, ...

Whereas, if I use - System.debug('contacts: ' + JSON.serialize(contacts)); - this gives me the related account name as well but in JSON format which is something like : contacts: [{"attributes":{"type":"Contact","url":"/services/data/v33.0/sobjects/Contact/00324000004kGRqAAM"},"AccountId":"001240000076MPFAA2","Account":{"attributes":{"type":"Account","url":"/services/data/v33.0/sobjects/Account/001240000076MPFAA2"},"Name":"test","Id":"001240000076MPFAA2"},"Id":"00324000004kGRqAAM", "Email": "[email protected]"},....

Is there any other way to retrieve the related records in Apex Test Classes as the same SOQL seems to be working okay in normal apex class? Please let me know your thoughts.

1
  • 5
    I think you need to debug specifically for Account.Name - the list debug is only showing the main object (in this case Contact) but if you so system.debug(contacts[0].Account.Name) you should see it Apr 27, 2015 at 20:15

1 Answer 1

1

System.debug() does not debug the values of related objects even if you have queried it in the SOQL. It only debugs the values of the fields which are queried and are present on that particular queried object.

This behavior is same in both normal apex classes and test classes.

If you want to debug the values of the related objects, you will have to explicitly debug that

List<Contact> contacts = new List<Contact>([Select Id, Email, AccountId, Account.Name From Contact]);
system.debug(contacts[0]);
system.debug(contacts[0].Account);

The first debug statement would display only the fields of Contact

DEBUG|Contact:{Id=0032400000593u8AAA, AccountId=001240000076MPFAA2,[email protected]}

The second debug statement would display the fields of related Account fields of that particular contact

DEBUG|Account:{Id=001240000076MPFAA2, Name=test}

And as mentioned in your question, you can debug the values of related object in single debug using JSON.serialize and JSON.serializePretty

Hence, instead of relying on the debug statements, you can assert the values or related values in test class to verify if the functionality you developed is working as expected.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .