Develop with and Test with Custom Metadata Types
Learning Objectives
- Access custom metadata types with code.
- Use Apex to test your custom metadata types.
Apex and Custom Metadata Types
Support_Tier__mdt Bronze; <CustomMetdataType>__mdt <VarName>;
Support_Tier__mdt [] minSpent = [SELECT Minimum_Spending__c FROM Support_Tier__mdt];
You can use custom metadata types in Apex the same way you use any standard Salesforce configuration object. However, you can also quickly transport records from development to subscriber orgs.
Test Custom Metadata Types
Typically, Apex tests don’t check for the existence of particular records. Because your org’s functionality doesn’t rely on specific accounts or opportunities, you don’t need to write tests for them. But when you deal with records that affect the way an org behaves, such is the case with custom metadata types, you do want to test those records.
If you’ve tested apps that use custom objects to hold app configuration records in the past, you might be familiar with the @IsTest(SeeAllData=true) annotation in Apex. This line of test code lets your Apex tests see all the records in your org, including data records like accounts and contacts. You might be wondering whether you need to take advantage of this practice to test your custom metadata types.
Luckily, you don’t. Custom metadata types are set up the same way as workflow and validation rules. Your Apex test classes can see custom metadata types and access their fields and records. Ultimately, your test cases for custom metadata types look more or less like most other Apex test cases.
public class CustomMetadataService { public CustomMetadataService() {} /** * This method instantiates a custom metadata record of type Support_Tier__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 Support_Tier__mdt getCustomMetadataRecord(String myName) { Support_Tier__mdt supportTier = new Support_Tier__mdt(); supportTier.DeveloperName = myName; return supportTier; } /** * This method retrieves a custom metadata record, changes a field, and returns it * to the caller, but does not update the database. */ public Support_Tier__mdt getChangedCustomMetadataRecord(String myNewName) { Support_Tier__mdt supportTier = [SELECT Id, DeveloperName from Support_Tier__mdt LIMIT 1]; supportTier.DeveloperName = myNewName; return supportTier; } }
Resources
- Developer Documentation: Metadata API Developer Guide > Custom Metadata Types
- Trailhead Module: Apex Testing
- Salesforce Blog: Testing Custom Metadata Types