I found a way to mock the error, using a static variable as a database, I can load a fake custom metadata record from the actual metadata, but with specific values for the test I need to do.
@IsTest
public class Object_1TriggerTest {
@IsTest
public static void Load_field_1_from_metadata(){
//Initialization and data loading
Object_1__c instance_of_object_1 = new Object_1__c(
Name = 'Test',
Picklist_1__c = 'picklist value 1'
);
MockMetadataUtils.insert_custom_metadata_mock();
//Test
Test.startTest();
insert instance_of_object_1;
Test.stopTest();
//ASSERTS
instance_of_object_1 = [
SELECT ID,Field_1__c
FROM Object_1__c
WHERE ID = :instance_of_object_1.Id
];
System.assertEquals('Value of metadata', instance_of_object_1.Field_1__c);
}
}
public class MockMetadataUtils {
public static List<example_metadata__mdt> rollupsumary = new List<example_metadata__mdt>();
public static void insert_custom_metadata_mock(){
example_metadata__mdt rollupsumary = new example_metadata__mdt();
Map<String,Object> fields = (Map<String, Object>)
JSON.deserializeUntyped(JSON.serializePretty(rollupsumary));
fields.put(
example_metadata__mdt.Field_1__c.getDescribe().getName(),
'picklist value 1'
);
fields.put(
example_metadata__mdt.Field_2__c.getDescribe().getName(),
'Value of metadata'
);
rollupsumary = (example_metadata__mdt)
JSON.deserialize(JSON.serialize(fields), example_metadata__mdt.class);
MockMetadataUtils.rollupsumary.add(rollupsumary);
}
}
public class Object_1TriggerHelper {
public static void updateSomeField(List<Object_1__c> test_Objects){
List<example_metadata__mdt> custom_metadata_records;
Map<String,example_metadata__mdt> custom_metadata_records_map = new Map<String,example_metadata__mdt>();
if(Test.isRunningTest()){
custom_metadata_records = MockMetadataUtils.rollupsumary;
}else{
custom_metadata_records = example_metadata__mdt.getAll().values();
}
for(example_metadata__mdt custom_metadata : custom_metadata_records){
custom_metadata_records_map.put(custom_metadata.Field_1__c, custom_metadata);
}
for(Object_1__c test_Object :test_Objects){
test_Object.Field_1__c = custom_metadata_records_map.get(test_Object.Picklist_1__c) != null ?
custom_metadata_records_map.get(test_Object.Picklist_1__c).Field_2__c :
null;
}
}
}