1

I have a custom metadata called Custom_Metadata__mdt.

I have one custom boolean field in that custom metadata called Custom_Boolean_Field__c.

I need to execute some logic only if value of Custom_Boolean_Field__c on custom metadata record with name 'default' is true.

I have a big class with much logic like this

public class Services{
    public static void methodToCallFromTrigger() {
        Custom_Metadata__mdt meta = [ SELECT Custom_Boolean_Field__c FROM Custom_Metadata__mdt WHERE MasterLabel = 'default'];
        if ( meta.Custom_Boolean_Field__c ) {
             // many many lines
        }
    }

}

If I uncheck Custom_Boolean_Field__c checkbox on Custom_Metadata__mdt default record then my coverage will drop to almost zero.

Is there a way to get 100% coverage even when value on Custom_Boolean_Field__c is false on Custom_Metadata__mdt default record?

2

You should rewrite your code in a following way

public class Services{
    public static Custom_Metadata__mdt defaultMeta { 
        get {
            if ( defaultMeta == null )
                defaultMeta = [ SELECT Custom_Boolean_Field__c FROM Custom_Metadata__mdt WHERE MasterLabel = 'default']; 
            return defaultMeta;
        } set; }

    public static void methodToCallFromTrigger() {
        if ( defaultMeta.Custom_Boolean_Field__c ) {
             // many many lines
        }
    }
}

}

then in your test before using metadata, you should run this code

Services.defaultMeta = (Custom_Metadata__mdt) JSON.deserialize( '{"Custom_Boolean_Field__c":true}', Custom_Metadata__mdt.class )

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.