1

I have created a utility (util) class that has a static find method that looks like this

List<SObject> find(String sObjetName, List<Id> listIds) 

How do I write a test that can be run in any Org

I mean I can't write a test like this

Account acc=new Account(Name='Test')
insert acc; // <= problem here account may have required fields

Test.startTest();
System.assertEquals(1,util.find('Account',new List<Id>{acc.Id}).size());
Test.stopTest();

Because required fields of an sObject may be different from one Org to an other

I need to write a test that can validate the method and run in any Org regardless of data model

Any idea ?

5

If this is part of a managed package then tests do not need to pass in subscriber org so not sure the effort is worth it of technical debt (object for the sake of a test).

Since standard objects, as you have found, may have requirements that you are unaware of to be able to instantiate and insert, the only assured way would be to use a custom setting as the object. If your package already has a custom setting then doing this will not add any debt.

Doing this would allow you to write the method while ensuring that the object is the same in every org

| improve this answer | |
  • No, It's not a managed package, It's just a util class to query object without rewriting soql query everytime... – benahm Mar 20 '17 at 16:32
  • @benahm - Ok, answer is still the same if you are installing in orgs that you do not have control over. – Eric Mar 20 '17 at 16:33
  • thanks for the Idea of custom settings, didn't thought about that – benahm Mar 20 '17 at 16:34
5

I solved the problem by using the accessible metadata objects, specially the ApexClass object

  1. I query the the ApexClass object with the name of my Utility class so I am sure to get an Id

  2. I use that Id to test my find method

Here is the code :

ApexClass apxc=[select Id from ApexClass where Name='util' limit 1];

Test.startTest();

System.assertNotEquals(null,apxc);
System.assertEquals(1,util.find('ApexClass',new List<Id>{apxc.Id}).size());

Test.stopTest();
| improve this answer | |
  • Solid answer! Never thought about the ApexClass object – Eric Mar 20 '17 at 18:27
  • That is not how you assert apxc is not null. There's a system.assertNotEquals method... – Adrian Larson Mar 20 '17 at 22:59
  • Not to mention it would never get to the assert if there were no records as it would throw the List has no rows for assignment error – Eric Mar 20 '17 at 23:27
  • 2
    I use Group as that is not customizable – cropredy Mar 20 '17 at 23:35
  • @AdrianLarson Yeah that's a more elegant way to do it, I changed my answer – benahm Mar 21 '17 at 8:18

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.