Home > front end >  How to write an APEX @test for a picklist method?
How to write an APEX @test for a picklist method?

Time:07-31

I was searching for answears but I couldn't find it. It might be a beginner question, anyhow I am stuck.
What I am trying to write is a test in Apex. Basically the Apex code gets field names from one specific object. Each fieldname will be shown in a picklist, one after the other (that part is a LWC JS and HTML file).
So, only want to test the Apex for the moment.
I don't know how to check that a list contains 2 parameters, and those parameters are object and field. Then the values are correctly returned, and I don't know how to continue.

Here's the Apex class with the method, which I want to test.

    public without sharing class LeadController {

        public static List <String> getMultiPicklistValues(String objectType, String selectedField) {

            List<String> plValues = new List<String>();
            Schema.SObjectType convertToObj = Schema.getGlobalDescribe().get(objectType);
            Schema.DescribeSObjectResult objDescribe = convertToObj.getDescribe();
            Schema.DescribeFieldResult objFieldInfo = objDescribe.fields.getMap().get(selectedField).getDescribe();
            List<Schema.PicklistEntry> picklistvalues = objFieldInfo.getPicklistValues();
            for(Schema.PicklistEntry plv: picklistvalues) {
              plValues.add(plv.getValue());
            }

            plValues.sort();
            return plValues;
        }
    }

I welcome any answers.
Thank you!

CodePudding user response:

This might be a decent start, just change the class name back to yours.

@isTest
public class Stack73155432Test {

    @isTest
    public static void testHappyFlow(){
        List<String> picklistValues = Stack73155432.getMultiPicklistValues('Lead', 'LeadSource');
        
        // these are just examples
        System.assert(!picklistValues.isEmpty(), 'Should return something');
        System.assert(picklistValues.size() > 5, 'At least 5 values? I dunno, whatever is right for your org');
        System.assert(picklistValues[0] < picklistValues[1], 'Should be sorted alphabetically');
        System.assert(picklistValues.contains('Web'), 'Or whatever values you have in the org');
    }
    
    @isTest
    public static void testErrorFlow(){
        // this is actually not too useful. You might want to catch this in your main code and throw AuraHandledExceptions?
        try{
            Stack73155432.getMultiPicklistValues('Account', 'AsdfNoSuchField');
            System.assert(false, 'This should have thrown');
        } catch(NullPointerException npe){
            System.assert(npe.getMessage().startsWith('Attempt to de-reference a null object'), npe.getMessage());
        }
    }
}
  • Related