Sub topic 8
Testing code that reads custom metadata
This chapter assumes you can write basic Apex tests with @IsTest and assertions. It also assumes you have read the earlier chapters on getInstance(), getAll(), and SOQL against custom metadata types. By the end you will be able to write tests that control custom metadata values, so they pass in any org.
Why custom metadata needs a testing strategy
Apex tests normally create their own data with DML (insert). Custom metadata records are different, because Apex cannot insert, update, or delete them with DML. A test cannot create a Feature_Flag__mdt record the way it creates an Account.
Tests can still read the custom metadata records that exist in the org. You do not need @IsTest(SeeAllData=true) for that. This creates two problems:
- Hidden dependency. A test that calls
FeatureFlags.isEnabled('New_Checkout')passes only if that record exists and has the right value. In a scratch org, a new sandbox, or a package installation, the record may be missing or different. - No control over variations. To test both the enabled and disabled paths, you would have to edit the org's records between runs.
The fix is a test seam. A test seam is a place in your production code where a test can substitute its own values. The sections below cover three kinds of seam, then how to test the Metadata API writer.
Strategy 1: an override map for simple lookups
For lookups by name, such as feature flags, add a @TestVisible static map to the class. @TestVisible lets a test class read and write a private member without making it public to production code.
public with sharing class FeatureFlags {
@TestVisible
private static Map<String, Boolean> testOverrides = new Map<String, Boolean>();
public static Boolean isEnabled(String flagName) {
if (testOverrides.containsKey(flagName)) {
return testOverrides.get(flagName);
}
Feature_Flag__mdt flag = Feature_Flag__mdt.getInstance(flagName);
return flag != null && flag.Is_Enabled__c;
}
}
@IsTest
private class FeatureFlagsTest {
@IsTest
static void overrideControlsFlagValue() {
FeatureFlags.testOverrides.put('New_Checkout', true);
System.assertEquals(true, FeatureFlags.isEnabled('New_Checkout'));
}
@IsTest
static void missingFlagIsDisabled() {
System.assertEquals(false, FeatureFlags.isEnabled('Does_Not_Exist'));
}
}Two details matter here.
- The override check runs before
getInstance(). A test can force a flag on or off whatever the org contains. missingFlagIsDisableduses a name that no org should contain. It tests thenullbranch, becausegetInstance()returnsnullfor an unknown developer name.
Static variables reset for each test method, so overrides in one test do not leak into another.
Test the code that uses the flag
The override matters most when you test a class that calls FeatureFlags. Suppose a checkout class has two paths:
public with sharing class CheckoutService {
public static String start() {
if (FeatureFlags.isEnabled('New_Checkout')) {
return 'new';
}
return 'legacy';
}
}
@IsTest
private class CheckoutServiceTest {
@IsTest
static void usesNewPathWhenFlagOn() {
FeatureFlags.testOverrides.put('New_Checkout', true);
System.assertEquals('new', CheckoutService.start());
}
@IsTest
static void usesLegacyPathWhenFlagOff() {
FeatureFlags.testOverrides.put('New_Checkout', false);
System.assertEquals('legacy', CheckoutService.start());
}
}Both paths are covered deterministically. The tests do not depend on the real record, so an admin changing the flag in production cannot break them.
Strategy 2: build records in memory
An override map works when you only need a single value. For richer configuration, such as a record with several fields, you can build a custom metadata record in memory. Apex does not allow a constructor with field values for these types, but JSON.deserialize() can produce a record that exists only in the running test.
@IsTest
private class InMemoryRecordTest {
@IsTest
static void buildsRecordWithoutDml() {
Map<String, Object> fields = new Map<String, Object>{
'DeveloperName' => 'Gold_Tier',
'Min_Amount__c' => 200,
'Percent__c' => 15,
'Is_Active__c' => true
};
Discount_Rule__mdt rule = (Discount_Rule__mdt) JSON.deserialize(
JSON.serialize(fields),
Discount_Rule__mdt.class
);
System.assertEquals(15, rule.Percent__c);
System.assertEquals('Gold_Tier', rule.DeveloperName);
}
}The record has no Id and is not stored anywhere. You can pass it to any method that accepts the type. Field API names in the JSON must match the type's fields exactly, and a mistyped name causes a deserialization error at test time.
Strategy 3: a seam for SOQL queries
SOQL against a custom metadata type always reads the org's real records. There is no way to intercept the query, so you put a seam around it. Load the records in one private method, and let a test replace the result.
public with sharing class DiscountService {
@TestVisible
private static List<Discount_Rule__mdt> testRules;
private static List<Discount_Rule__mdt> loadRules() {
if (testRules != null) {
return testRules;
}
return [
SELECT DeveloperName, Min_Amount__c, Percent__c
FROM Discount_Rule__mdt
WHERE Is_Active__c = true
ORDER BY Min_Amount__c DESC
];
}
public static Decimal percentFor(Decimal orderTotal) {
for (Discount_Rule__mdt rule : loadRules()) {
if (orderTotal >= rule.Min_Amount__c) {
return rule.Percent__c;
}
}
return 0;
}
}
@IsTest
private class DiscountServiceTest {
private static Discount_Rule__mdt makeRule(String name, Decimal minAmount, Decimal percent) {
Map<String, Object> fields = new Map<String, Object>{
'DeveloperName' => name,
'Min_Amount__c' => minAmount,
'Percent__c' => percent,
'Is_Active__c' => true
};
return (Discount_Rule__mdt) JSON.deserialize(
JSON.serialize(fields),
Discount_Rule__mdt.class
);
}
@IsTest
static void picksLargestQualifyingTier() {
DiscountService.testRules = new List<Discount_Rule__mdt>{
makeRule('Gold', 200, 15),
makeRule('Silver', 100, 10)
};
System.assertEquals(15, DiscountService.percentFor(250));
System.assertEquals(10, DiscountService.percentFor(150));
}
@IsTest
static void noDiscountBelowLowestTier() {
DiscountService.testRules = new List<Discount_Rule__mdt>{
makeRule('Silver', 100, 10)
};
System.assertEquals(0, DiscountService.percentFor(50));
}
@IsTest
static void emptyRuleListGivesZero() {
DiscountService.testRules = new List<Discount_Rule__mdt>();
System.assertEquals(0, DiscountService.percentFor(500));
}
}Note the difference between null and an empty list. The check testRules != null lets a test supply an empty list to simulate "no rules configured". If you tested testRules.isEmpty() instead, that scenario would fall through to the real query.
Testing the Metadata API writer
The FlagUpdater class from the earlier chapter enqueues an asynchronous deployment. A unit test should not rely on a real deployment completing. Instead, test the two parts separately:
- The callback.
handleResultis an ordinary method. You can build aMetadata.DeployResult, set its status, and call the method directly. - The enqueue call. Check only that your method builds a deployment and returns without throwing. Do not assert on the final record value, because the test cannot observe the deployment's effect.
@IsTest
private class FlagUpdaterTest {
@IsTest
static void callbackHandlesSuccess() {
Metadata.DeployResult result = new Metadata.DeployResult();
result.status = Metadata.DeployStatus.Succeeded;
Test.startTest();
new FlagUpdater().handleResult(result, new Metadata.DeployCallbackContext());
Test.stopTest();
System.assert(true, 'Callback completed without an exception');
}
@IsTest
static void callbackHandlesFailure() {
Metadata.DeployResult result = new Metadata.DeployResult();
result.status = Metadata.DeployStatus.Failed;
result.errorMessage = 'Simulated failure';
new FlagUpdater().handleResult(result, new Metadata.DeployCallbackContext());
System.assert(true, 'Failure branch completed without an exception');
}
}These tests cover both branches of the callback, which usually matters for coverage. If your callback does something observable, such as inserting a log record, assert on that instead of System.assert(true).
Choosing a strategy
| Situation | Seam to use | Reason |
|---|---|---|
| Look up one value by developer name | `@TestVisible` override map | Simplest, and no record construction |
| Need several fields from a record | In-memory record via `JSON.deserialize` | Keeps the real field types |
| Production code uses SOQL | `@TestVisible` list around the query | A query cannot be intercepted |
| Deployment callback | Call `handleResult` directly | Deployments are not observable in a test |
Common mistakes
- Relying on org records. A test that passes in your sandbox and fails in a scratch org usually depends on a record that was never deployed. Prefer overrides for anything the assertion depends on.
- Putting test logic in production paths with
Test.isRunningTest(). A branch such asif (Test.isRunningTest()) return true;hides real behavior. A@TestVisibleseam keeps production logic identical in tests. - Making the override
public. Useprivateplus@TestVisible, so only tests can change it. - Testing only the happy path. Always test the missing-record case, since
getInstance()returnsnullfor an unknown name and an uncheckednullcauses aNullPointerException.
Exercise
A class TaxService reads Tax_Strategy__mdt.getInstance(regionCode) and throws an IllegalArgumentException when the record is missing. You want a test for the missing-record case that passes in every org. What do you need to do, and why do you not need a seam?
Show answer
Call TaxService.calculate('ZZ_NOT_A_REGION', 100) inside a try/catch (or assert the thrown exception type) and check that an IllegalArgumentException occurs. No seam is needed because the test relies on the record being absent, not present. An unknown developer name makes getInstance() return null in any org. A seam is needed only when the test depends on a record existing with a particular value.