1

Below is the excpetion,

System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, Apex tests cannot be enqueued during a test.

It happens when the code that is inserting records in the ApexTestQueueItem sObject and that code is invoked from the test class.

1

Inserting a record of ApexTestQueueItem and providing ApexClassId queues with the Apex Unit test for that class to be run in a normal environment.

Now when you try to queue a test class from already running test class you run into this exception. If this was possible we might end up with testClass queuing test class leading to infinite loop and wasting expensive resource. In order to avoid this salesforce throws a DMLException when you try to do so.

Thus you have to use isRunningTest

if(Test.isRunningTest()){
    dont insert;
} else{
  do insert;//
}
  • Thanks for your reply. But what will be next? My entire code after return will not be covered, which depends on the test class enqueue. – allgood Oct 31 '18 at 7:12
  • Can you provide more code snippet? We might be able to mock it? @allgood – Pranay Jaiswal Oct 31 '18 at 10:24
  • You can suppose, one of my apex class is getting all test classes and then inserting those test classes in the ApexTestQueueItem sObject where these will be queued to run. And then I do something based on the test run result. So, If I will keep my code that keep ApexClasses in ApexTestQueueItem sobject in IsRunningTest, that means the code after that will not be covered. – allgood Oct 31 '18 at 10:30
  • Just don't insert it, rest u can do... – Pranay Jaiswal Oct 31 '18 at 10:44
  • Rest all depends on this only. Then I need to put IsRunningTest at some other places too. Which is not a recommend/good way to do now a days. – allgood Oct 31 '18 at 11:06

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.