Custom Metadata Type (in Apex Test Class)

3D Render of Cloud Drive Icon
  • Custom Metadata can be accessed from Apex using SOQL

List < Service_Provider__mdt >serviceMetadat = SELECT Object_Type__c, Provider_ Field__c FROM Service_Provider__mdt

  • Apex code can create, read, and update (but not delete) custom metadata records, as long as the metadata is subscriber-controlled and visible from within the code’s namespace.
  • We can edit records in memory but not upsert or delete them. Cannot do DML operations.

Here is an example to use set values of Custom metadata in Apex that can be used in Apex Test.

public class CustomMetadataService {

public CustomMetadataService() {}


* This method instantiates a custom metadata record of type Service_Provider__mdt

* and sets the DeveloperName to the input String.

* The record is not inserted into the database,

* and would not be found by a SOQL query.


public Service_Provider__mdtgetCustomMetadataRecord(String myName) {

Service_Provider__mdtserviceProvider = new Service_Provider__mdt();

serviceProvider.DeveloperName = myName;

return serviceProvider;



* This method retrieves a custom metadata record, changes a field, and returns it

* to the caller, but does not update the database.


public Service_Provider__mdtgetChangedCustomMetadataRecord(String myNewName) {

Service_Provider__mdtserviceProvider = [SELECT Id, DeveloperName from Service_Provider__mdt LIMIT 1];

supportTier.DeveloperName = myNewName;

return serviceProvider;



Share on

Share on facebook
Share on twitter
Share on linkedin

Related Posts

LWC vs Aura

LWC LWC uses core Web Components standards (Native browser APIs) and provides only what’s necessary to perform well in browsers supported by Salesforce. Because it’s

Marketing Cloud Basics

It enables you to know your customer, personalize with intelligence, and engage across the entire journey. It’s the only integrated customer engagement platform that enables


Prerequisite: Enable “Dev Hub” in your Production Org. 1. Log in to the Dev Hub To authorize the Dev Hub, use the web login flow

Platform Events

Platform event is based on Event-driven architecture. Unlike request-response communication models, software architecture built on an event-driven model decouples event producers from event consumers, thereby