1

When trying to insert a custom metadata record within the test it gives me the following error

@IsTest
public class Object_1TriggerTest {
    @IsTest
    public static void Load_field_1_from_metadata(){
        //Initialization and data loading
        Object_1__c instance_of_object_1 = new Object_1__c(
            Name = 'Test',
            Picklist_1__c = 'picklist value 1'
        );

        Metadata.CustomMetadata customMetadata =  new Metadata.CustomMetadata();
        customMetadata.fullName = 'example_metadata__mdt.MetadataRecordName';

        Metadata.CustomMetadataValue customField = new Metadata.CustomMetadataValue();
        customField.field = 'Field_1__c';
        customField.value = 'picklist value 1';

        customMetadata.values.add(customField);

        Metadata.DeployContainer mdContainer = new Metadata.DeployContainer();
        mdContainer.addMetadata(customMetadata);

        // Enqueue custom metadata deployment
        Id deployRequestId = Metadata.Operations.enqueueDeployment(mdContainer, null);

        //Test
        Test.startTest();
        insert instance_of_object_1;
        Test.stopTest();
        //ASSERTS
        instance_of_object_1 = [SELECT ID,Field_1__c FROM Object_1__c WHERE ID = :instance_of_object_1.Id];
        System.assertEquals('Value of metadata', instance_of_object_1.Field_1__c);
    }
}

FATAL_ERROR System.AsyncException: Metadata cannot be deployed from within a test

0

1 Answer 1

1

Just use dependency injection wherever you query for the metadata to consume it. The simplest form looks something like below:

public with sharing class MyService
{
    @TestVisible static List<My_Metadata__mdt> metadata = My_Metadata__mdt.getAll();
    public static void myMethod()
    {
        for (My_Metadata__mdt record : metadata)
        {
            // consumer logic
        }
    }
}

Your test can simply overwrite the getAll result (or query if you use one).

@IsTest
static void testMyMethod()
{
    MyService.metadata = new List<My_Metadata__mdt>
    {
        new My_Metadata__mdt(/*mocked fields*/)
    };
    
    Test.startTest();
        MyService.myMethod();
    Test.stopTest();
    
    // assertions
}

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