[SalesForce] Qualified API Name returns null in Test context for Custom Metadata

Winter 19 release provides ability to instantiate the custom metadata in apex .This seems to be useful to generate data for test classes .

However when we have metadata relationship entity or field entity relationship the QualifiedName comes as null in Test class .

Lets take an example with the below code in a Test class .For now use execute Anonymous via Dev console

Relationship__mdt relationship = new Relationship__mdt(
        DeveloperName = 'Test',
        Active__c = true,
        Object__c = 'Account',
        AccountRelationship__c = 'ParentId'
    );
 system.debug('###'+relationship.Object__r.qualifiedAPIName);

In the above code Object__c is of type metadataRelationship (Object definition ) and AccountRelationship__c is also of metadataRelationship type (Field Entity Definition) .

When i do relationship.Object__r.QualifiedAPIName in test context I receive null and not 'Account'.

Similarly when i do relationship.AccountRelationship__r.QualifiedAPIName in test context I receive null and not ParentId .

This makes it not helpful again for use cases where metadata data has entity relationship and the code uses QualifiedName .

Is it a bug or I am overlooking something ?

Best Answer

You still need to use JSON construction if you want to set parent attributes without a true query for the records.


Non Functional Code

EntityDefinition sourceObject = [SELECT QualifiedApiName FROM EntityDefinition LIMIT 1];
MyMapping__mdt mapping = new MyMapping__mdt(
    Source_Object__r = sourceObject
);

Error

Field is not writeable: MyMapping__mdt.Source_Object__r


Functional Code

Map<String, Object> mockMapping = new Map<String, Object>
{
    'attributes' => new Map<String, Object>
    {
        'type' => 'MyMapping__mdt '
    },
    'Source_Object__r' => new Map<String, Object>
    {
        'attributes' => new Map<String, Object>
        {
            'type' => 'EntityDefinition'
        },
        'QualifiedApiName' => 'Account'
    }
};
MyMapping__mdt mapping = (MyMapping__mdt)JSON.deserialize(
    JSON.serialize(mockMapping), MyMapping__mdt.class
);
system.debug(mapping.Source_Object__r.QualifiedApiName);

Log

Account