I have the following code in a test class

parent__c parent = new parent__c();
insert parent;

child__c child = new child__c();
child.parent__c = parent.Id;
insert child;

In the DataBase, the relationship from the parent to the child is called child__r and it is populated for many records.

If I try

System.debug('@@@@@ --> '+[SELECT Id, parent__c FROM child__c]);

I get the child Id and parent Id correctly, but if I try

System.debug('@@@@@ --> '+[SELECT Id, (SELECT Id FROM child__r) FROM parent__c]);

Only the parent is returned, in other words, the relationship is not populated and

System.debug('@@@@@ --> ' + parent.child__r);

is empty.

In the tested class, an If statement has in the condition "!child__r.isEmpty()", how can I populate the relationship?

P.S. I cannot use isRunningTest() since then I could not enter in the ELSE statement.

  • Is it in a loop? System.debug('@@@@@ --> ' + parent.child__r); – m Peixoto Aug 5 '19 at 10:58
  • This is not in a loop, I have also tried the full query System.debug('@@@@@ --> '+[SELECT Id, (SELECT Id FROM child__r) FROM parent__c]); – Koala Aug 5 '19 at 12:18

I can't seem to reproduce your issue. But can explain a little bit what I have tried.

Below is a simple test method to reproduce your scenario:

public class SampleUnitTest {
    public static void testSample() {
        Account acc = new Account();
        acc.Name = 'test acc';
        insert acc;

        Contact con = new Contact();
        con.accountId = acc.Id;
        con.lastName = 'tln';
        insert con;

        acc = [Select Id, Name, (Select Id From Contacts) From Account Where Id = :acc.Id];

        System.debug('Contacts are: ' + acc.Contacts);

        for(Contact c: acc.Contacts) {

Please note that if you debug acc, it doesn't show the contact information there.

However, if you use a do a System.debug(acc.Contacts) or do the debug inside a loop, it will print the related information out.

I am not quite sure whether you have tried both or only tried System.debug(acc). If the later one was the case, it simply doesn't mean your related list is empty.

  • Maybe this case works because you used a standard relation, in my case I assure you that parent.child__r is empty. As I stated in the question, I tried System.debug('@@@@@ --> ' + parent.child__r); – Koala Aug 5 '19 at 12:14

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.