Find your content:

Search form

You are here

Run anonymous apex as if it were a test case


Is there any way to run anonymous apex so that it is treated the same way as a unit test?

Sometimes it would be ideal to just try some code out and know that any DML operations that get performed won't be committed. I wouldn't expect callouts to occur or emails to be sent.

This would also allow individual test methods to be run from a class. So if one method in a dozen or so is failing you could re-run it and get a more concise log.

I have considered using transaction control and just doing a rollback, but that doesn't give the full advantage of running as a test.

Attribution to: Daniel Ballinger

Possible Suggestion/Solution #1

As a stub answer assuming no one has a way to do this or something equivalent I've raised the following idea: Run anonymous apex as if it were a test case

When I have previously tried to run test cases from anonymous apex I get the error: "System.TypeException: Cannot call test methods in non-test context"

Attribution to: Daniel Ballinger

Possible Suggestion/Solution #2

It's not a complete answer but you can always rollback dml operations yourself:

System.Savepoint sp = Database.setSavepoint();
try {
    //all you anonymous code
} catch(DmlException e) {
} finally {

You will still have the problem of callouts and emails being sent, but if these are not a factor it will be sufficient

Attribution to: Daniel Blackhall

Possible Suggestion/Solution #3

Another method similar to Daniels is to just throw an arbitrary exception at the end of your script; This will have the same effect and roll back the whole transaction.

The difference is that since mailouts are queued, but not sent until the end of a successful transaction, the uncaught exception will cause Salesforce to cancel sending the mail queue.

for example

throw new NullPointerException();

Attribution to: James Davies

Possible Suggestion/Solution #4

As of vesion 0.22.81, the force cli supports running anonymous apex in a test context by wrapping it in a temporary class and using compileAndTest:

$ force apex -test
>> Start typing Apex code; press CTRL-D(for Mac/Linux) / Ctrl-Z (for Windows) when finished
List<Account> accounts = [SELECT Id FROM Account];
System.assertEquals(3, accounts.size(), 'number of accounts');

>> Executing code...
ERROR: System.AssertException: Assertion Failed: number of accounts: Expected: 3, Actual: 152
$ echo $?

Attribution to: xn.
This content is remixed from stackoverflow or stackexchange. Please visit

My Block Status

My Block Content