Skip to main content

We want to cache custom metadata in an Apex Class by using the Salesforce "Platform Cache". 

Since the code is deployed to one production org having custom meta and one production org which does not have custom meta we cannot guarantee that any custom metadata exists.  

We use dynamic queries to deliver a List of sObject since we do not want to cache more than necessary.

It is necessary to run the tests in a scratch org. 

 

What is the best solution for writing the Apex tests WITHOUT actually deploying the Custom Metadata, considering the test coverage of 75%.

1 réponse
  1. 2 mars, 09:08

    Hi @Jürgen Kortgen

      When using Platform Cache to cache Custom Metadata, and your code must run in orgs where metadata may or may not exist (including scratch orgs), the cleanest solution is to abstract metadata access behind an interface and mock it in tests.  

    Example: 

    1. Create an interface

    public interface ICustomMetadataProvider {    List<sObject> getMetadata();}

    2. Production implementation

    public class CustomMetadataProvider implements ICustomMetadataProvider {    public List<sObject> getMetadata() {        return Database.query(            'SELECT DeveloperName FROM My_Metadata__mdt'        );    }}

    3. Inject provider into cache service

    public class MetadataCacheService {    @TestVisible    static ICustomMetadataProvider provider;    private static ICustomMetadataProvider getProvider() {        return provider == null            ? new CustomMetadataProvider()            : provider;    }    public static List<sObject> getMetadataFromCache() {        String key = 'MyMetaKey';        List<sObject> result =            (List<sObject>) Cache.Org.get(key);        if (result == null) {            result = getProvider().getMetadata();            Cache.Org.put(key, result);        }        return result;    }}

    4. Mock in tests

    @IsTestprivate class MetadataCacheServiceTest {    private class MockProvider        implements ICustomMetadataProvider {        public List<sObject> getMetadata() {            return new List<sObject>{                new Account(Name='Test')            };        }    }    @IsTest    static void testCache() {        MetadataCacheService.provider =            new MockProvider();        List<sObject> result =            MetadataCacheService.getMetadataFromCache();        System.assertEquals(1, result.size());    }}

      

    Kindly mark this as accepted answer if you find this as helpful! 

     

    Thanks, 

    Anandh T

0/9000