Running Test Classes From Apex Code


Salesforce provides a few objects for working with test classes directly from apex code.

It provides the ability to schedule test runs with a list of test classes and the ability to query the test result. Seems the main part which is not supported is the code coverage. The result contains only information regarding success/failure and errors in case of failure. For the code coverage, we will need to use another API (for example, tooling API). 

Basically, to set up a test run, all we need to do is to insert ApexTestQueueItem records. Each record indicate a test class that should be running. Creating several items in the same transaction will link them all under the same test.


In the following demo, I tried to keep it simple. Therefore, I'm using native apex without an API. I'm using a web components that allow me to select a list of test classes, set specific intervals and schedule it to run at a specific time.

Clicking the Run Test button set up a job to run which first creates the ApexTestQueueItem items and then set a second job to check the result in 5 minutes, as the tests run asynchrounsly. 

When the job running, it first checks if all the related ApexTestQueueItem items were completed. If it does, then it queries the result and reports any failure that was found during the test. If not all tests are completed, it set job to check it again in 5 minutes. 

  • 5 minutes might be too low value if I'm running all tests, but for the demo purpose it is fine.


Another issue that you need to consider: the code using the standard object ApexClass to get a list of classes, but it cannot indicate if a specific class is a test class. In the code, I'm getting the class content and check if it contains the text @istest, but it is not 100% correct.


Also note that for the solution I'm a free app: Asynchronous Process Manager / Creator, which allow to easily set and monitor background jobs and it provides some other core components that are used and saves some efforts.


Can view the full code in git


No comments:

Post a Comment

Retire of Permission on Profiles

If you are working as a Salesforce admin/developer you've probably heard somewhere that Salesforce is planning to make a significant cha...