0

I have task to test fields from custom class and i need to find all the fields are exist and return expected data. ex:

Class Person{ 
     String Name {get;set;} 
     integer Age {get;set;}
}
//in Test
integer fieldCount =0;
Person p = new Person();
p.Name = 'John';
p.Age = 43;
integer fieldCount = <logic to retrieve field count>
Assert.assertEquals(2,fieldCount);

I want to fetch all the class fields for given instance and assert their values, all I am finding is Schema.getGlobalDescribe() but not finding related to Apex class!. Any help will be appreciated.

2

Apex does not support reflection so there's no built-in mechanism available in the Apex runtime to let you do this.

You would need to use the tooling API to query the ApexClass and its SymbolTable. You'll find more information around the tooling API and how to invoke it in the documentation. It is technically possible, if a bit painful, to call the API from Apex. There are even some libraries to help with this, such as Andrew Fawcett's one.

1

Does this help?

class Person {
    String name;
    String age;
}

Person p = new Person();
p.age = 45;
p.name = 'foo';

String pSerialized = JSON.serialize(p);
Map<String,Object> valsByProperty = (Map<String,Object>) JSON.deserializeUntyped(pSerialized);
System.assertEquals(2,valsByProperty.size());
System.assertEquals(45, (Integer) valsByProperty.get('age');

When you serialize, you can exclude null values in the second arg

Reference: JSON support in Apex doc

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.