Run anonymous apex as if it were a test case

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) {
    System.debug('DmlException='+e);
} finally {
    Database.rollback(sp);
}

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


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

doStuffHere();
throw new NullPointerException();

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
Test.startTest();
List<Account> accounts = [SELECT Id FROM Account];
System.assertEquals(3, accounts.size(), 'number of accounts');
Test.stopTest();

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

Tags:

Apex

Unit Test