1

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

0

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() ? 'Fake Job Id' : Metadata.Operations.enqueueDeployment(mdContainer, callback);

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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