4

We are following Deploy Metadata example from the documentation

// Setup custom metadata to be created in the subscriber org.
Metadata.CustomMetadata customMetadata =  new Metadata.CustomMetadata();
customMetadata.fullName = 'MetadataTypeName.MetadataRecordName';

Metadata.CustomMetadataValue customField = new Metadata.CustomMetadataValue();
customField.field = 'customField__c';
customField.value = 'New value';

customMetadata.values.add(customField);

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

// Setup deploy callback, MyDeployCallback implements
// the Metadata.DeployCallback interface (code for
// this class not shown in this example)
MyDeployCallback callback = new MyDeployCallback();

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

but we can't cover that method with unit tests, when we try to call this method in unit test, since we receive the following error

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

1 Answer 1

8

You might use Test.isRunningTest(). It is considered to be a bad practice to use it but for covering this case this is the only option for now.

Hopefully in the future Salesforce will add some Deploy Mock Interface for this use case which we will be able to use instead of Test.isRunningTest()

So you need just update your line

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

to

// Enqueue custom metadata deployment
Id jobId = Test.isRunningTest() ? '001FAKEJOBID' : Metadata.Operations.enqueueDeployment(mdContainer, callback);
0

You must log in to answer this question.

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