2

I am using a Custom Metadata Type in my Managed Package to control the execution of a Trigger. When I deploy the Managed Package, I will have the setting disabled. This causes my Tests to fail.

How do I write my Apex Test so that it either enables the Custom Metadata Type setting for the tests then disables before publishing or gets around the setting?

1

The approach to test custom metadata has been explained in the below blog

https://developer.salesforce.com/blogs/engineering/2015/05/testing-custom-metadata-types.html

The approach highlights

1)Create a custom field TestCase__c on the custom metadata

2)Create a class with static string as below

public class TestContext {
  public static String testCase {public get; public set;}
}

3)When you query for your custom metadata in your application’s code, include TestCase__c in the WHERE clause of the query:

OurCustomMetadata__mdt[] rows = [SELECT QualifiedApiName, Field1__c
 FROM OurCustomMetadata__mdt
 WHERE TestCase__c = :TestContext.testCase];

4)In general, TestContext.testCase will be null, so this query will return real results. In tests, however, you can set the static variable to the test case you want, and retrieve exactly the correct records.

public static testmethod void testWelcomePageWorksWithTestCase1() {
TestContext.testCase = 'TestCase1';
  /* test the Welcome page */
}
  • 1
    Excellent, thanks for pointing me to this. I was able to implement the tests successfully. Cheers. – Jesse Miller Nov 30 '15 at 5:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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