7

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.

2

4 Answers 4

7

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

1
  • Thanks. I had considered using transactions. And as you say, this gives some of the advantages of running as a test. Aug 14, 2012 at 22:11
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
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
2
2

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();
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"

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .