0

I have a function that returns the list of all custom objects that are currently present in the org, as listed below.

 @AuraEnabled
    public static List<String> getCustomObjectNames()
    {    
        List<String> objectNamesCustom = new List<String>();
        
        List<Schema.SObjectType> objList = Schema.getGlobalDescribe().Values();     
        for(Schema.SObjectType obj : objList)
        {
            if(obj.getDescribe().isCustom())
                objectNamesCustom.add(obj.getDescribe().getName());
        }
        
        return objectNamesCustom;
    }

I am clueless as to how this may be unit tested as the list of custom objects is unique to every org and custom object definitions may only be added via object manager (not with Apex or SOQL). So how does one go about writing a unit test for something like this?

@IsTest
private class CrossReferencesAPITest
{
  @IsTest
  testGetCustomObjectNames()
  {
    // What to do? I can't create custom object definitions and then fetch them using my function, can I?
  }
}

On a related note, how does one go about testing functions that require you to fetch meta data specific to an org, which may only be added or modified using the object manager (not with dynamic Apex or SOQL)? Another function I have fetches the list of all parent entities for a specified object API name. In cases like this, how does one go about writing unit tests? I'd appreciate it if actual examples are provided.

1 Answer 1

1

I'm assuming you are wanting to deploy this as a managed package, and hence why you do not know if the target organization would have any custom objects? If so, then I would make the suggestion of including at least one custom object in your package (even if that object doesn't have any data in it). Then simply call getCustomObjectNames() in your test class and it should cover the lines of code regardless of whether or not the target organization has any custom objects.

Another trick would be to not separate the if-line in the code:

 if ( obj.getDescribe().isCustom() ) objectNamesCustom.add(obj.getDescribe().getName());

Having it as a single line would allow the test coverage even when the "if" never evaluates to true.

You must log in to answer this question.

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