I have used metadata APIs to create new values to picklist values using apex. But unfortunately, I am not able to understand how to write the test class for the same.

Can someone help me

This is my code

    public static void addNewPiklistValue(String value) {
        Refined_MetadataService.MetadataPort service = new Refined_MetadataService.MetadataPort();
        service.timeout_x =120000;
        service.SessionHeader = new Refined_MetadataService.SessionHeader_element();
        service.SessionHeader.sessionId = UserInfo.getSessionId();
        Refined_MetadataService.CustomField customFieldOfPO = 
            (Refined_MetadataService.CustomField) service.readMetadata('CustomField', new String[] { 
                'SBQQ__ProductOption__c.Target__c' }).getRecords()[0];    
        Refined_MetadataService.CustomValue valueToAdd = new Refined_MetadataService.CustomValue();
        valueToAdd.fullName = value;
        Refined_MetadataService.SaveResult result = service.updateMetadata(new Refined_MetadataService.Metadata[] 

1 Answer 1


Web service calls such as this can be mocked so your test case could look something like this:

private class MetadataServiceTest {

    private class MetadataServiceMock implements WebServiceMock {

        Integer callCount = 0;

        public void doInvoke(
            Object stub,
            Object request,
            Map<String, Object> response,
            String endpoint,
            String soapAction,
            String requestName,
            String responseNS,
            String responseName,
            String responseType
        ) {
            // Basic mocking only
            if (request instanceOf MetadataService.deleteMetadata_element) {
                MetadataService.deleteMetadataResponse_element res =
                    new MetadataService.deleteMetadataResponse_element();
                res.result = new MetadataService.DeleteResult[] {};
                response.put('response_x', res);
            } else {
                System.assert(false, 'unexpected request ' + request);

    static void delete_ok() {

        MetadataServiceMock mock = new MetadataServiceMock();
        Test.setMock(WebServiceMock.class, mock);

        Template2__mdt template = queryTemplate();

        String message = TemplatesTabController.deleteTemplate(template.Id);
        System.assertEquals(null, message);

        // Delete done
        System.assertEquals(1, mock.callCount);


This code relates to a custom metadata type not picklist metadata but your pattern will be similar with different types used.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .