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.
-
Please see a similar question Unit Test - Creating Custom Metadata– SarveshCommented Sep 20, 2019 at 9:08
-
@Sarvesh the question is related to the custom objects, not custom metadata. Or is that the same solution?– Eugene VabishchevichCommented Sep 20, 2019 at 9:14
-
For Custom setting How to get Custom Settings in the Apex Test code?– SarveshCommented Sep 20, 2019 at 9:21
-
@Sarvesh did you read my original message? All your references are not relevant.– Eugene VabishchevichCommented Sep 20, 2019 at 9:43
1 Answer
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.:
@IsTest
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.
PS
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. Commented Sep 20, 2019 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 CCommented Sep 20, 2019 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. Commented Sep 20, 2019 at 12:03