If yes, how to do that? Sorry, sounds trivial, but couldn't google it out.

  • 1
    What do you mean by invoking test?You have left a lot for imagination. – Mr.Frodo Jun 7 '16 at 5:17
  • To run test methods, and receive some return info. – user3443471 Jun 7 '16 at 5:22
  • So you want to run tests methods from your code and not from the UI?? – Mr.Frodo Jun 7 '16 at 5:28
  • Yes, exactly... – user3443471 Jun 7 '16 at 5:28

Yes you can invoke test classes from apex. All you need to know is the Test class id. You need to create a 'ApexTestQueueItem' record with id of test class that you wanna run. See the below example.

ApexClass[] testClasses =[SELECT Id FROM ApexClass WHERE Name ='LoggerTest'];

if (testClasses.size() > 0) {
        ApexTestQueueItem[] queueItems = new List<ApexTestQueueItem>();
        for (ApexClass cls : testClasses) {

            queueItems.add(new ApexTestQueueItem(ApexClassId=cls.Id));

        insert queueItems;

You can invoke test classe using Rest/SOAP api as well, take a look at the below given doc.


  • If my answer helped, please upvote and mark your question as solved, it will help with similar queries reach results fast. – Pranay Jaiswal Jun 7 '16 at 5:35
  • 1
    Yes, I had no reputation to do this, but now I have. Thumbs up! – user3443471 Jun 7 '16 at 17:25
  • :) keep the good work flow – Pranay Jaiswal Jun 8 '16 at 5:27

You can run tests asynchronously using ApexTestQueueItem and ApexTestResult. These objects let you add tests to the Apex job queue and check the results of the completed test runs. This process enables you to not only start tests asynchronously but also schedule your tests to execute at specific times by using the Apex scheduler. See Apex Scheduler for more information.

Insert an ApexTestQueueItem object to place its corresponding Apex class in the Apex job queue for execution. The Apex job executes the test methods in the class. After the job executes, ApexTestResult contains the result for each single test method executed as part of the test.


  • This code itself cannot be tested, correct? – Adrian Larson Jun 7 '16 at 19:28
  • @AdrianLarson Although i have not found any doc which state this or any test class for this kind of code.But my guess is you are right.If you would create a test class for this code at the time of insertion in the queue it will throw error Apex tests cannot be enqueued during a test..May be there is some workaround for this and i would love to try this scenario as soon as i will have time. – Mr.Frodo Jun 8 '16 at 5:10

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.