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=sean@edge.com, 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": "test@example.com"},....

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.

  • 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 – BritishBoyinDC Apr 27 '15 at 20:15

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]);

The first debug statement would display only the fields of Contact

DEBUG|Contact:{Id=0032400000593u8AAA, AccountId=001240000076MPFAA2,Email=sean@edge.com}

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.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.