We are building a package that creates custom setting with reference to custom objects. Then we use settings to create records for these custom objects. How we can create unit test in the package for such functionality? As I know we can't create metadata in the unit test.


This answer assumes you are asking about Custom Settings not Custom Metadata Types.

You can set up your custom settings in your test code. Presumably your product code varies depending on those settings, so individual test methods will set up different permutations, e.g.:

static void myTest() {

    MyCustomSetting__c sob = MyCustomSetting__c.getIntance();
    sob.MyField__c = 'Abc';
    sob.MyField2__c = true;
    upsert sob;


See the various methods available - Custom Setting Methods.

You can move the code out into a separate method or class if there are a lost of permutations.


Couple of articles on Custom Metadata Types; old one Testing Custom Metadata Types; newer feature that may help Instantiate Custom Metadata Types in Apex.

  • The thing is that I want to create some custom objects records in different logic in the package. What I want to do is to save custom object in the custom setting. For example: save "Test_Object__c". And then select this setting in the code and initialize the Test_Object__c. Sep 20 '19 at 10:16
  • Well, a custom setting can be manipulated in a unit test using Apex just as a custom object can. So specifically, what is blocking you?
    – Keith C
    Sep 20 '19 at 10:50
  • Yes, because we are displaying custom objects only (without custom settings). In theory we can add empty custom object for unit tests but I don't think that is good idea. Sep 20 '19 at 12:03

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.