4

Suppose I have test class TestClassName with two test methods:

@isTest
private class TestClassName {
    static testMethod void testMethodName() {
         // DML to insert data 
    }
    static testMethod void testMethodName() {
        // is inserted data available here?
    }
}

In other words, are all test methods isolated — as if a complete tearDown was performed after the execution of each test method?

2

1 Answer 1

4

Crap, I've misread the question! Yes, they're isolated!


There are no equivalents of jUnit's setUp and tearDown but each method is independent of other methods. If you need setUp, you have to write it yourself - create a small private static void prepareTestData() with all your DML and explicitly call it at the beginning of your test methods.

Actually it might be marked as public - will save you time if you can reference them from other test classes. It's still within a test class so it's unaccessible from regular code and does not count towards Apex storage usage.

There used to work a neat trick that would let you have some kind of "initialization block":

@isTest
private class TestClassName {
    private static Acount testAccount;

    static {
       testAccount = new Account(Name = 'science, baby');
       insert testAccount;
    }

    static testMethod void testMethodName() {
    }
    static testMethod void testMethodName() {
    }
}

This doesn't work anymore :( If you have only 1 test method it should work, but each subsequent one will not see the data crated in this static block.

2
  • Thanks! Although, my question is whether I can rely on there being no side effects. I don't mind preparing my data, as long as I'm safe from data from one test not influencing other tests.
    – ipavlic
    Feb 14, 2013 at 15:46
  • I'm an idiot ;) Yes, you'll be completely safe, all variables will be reset, transactions rolled back etc. But if you use @seeAllData=true and need exclusive access to some resources you must bear in mind many tests can run at same time - read about SELECT...FOR UPDATE syntax.
    – eyescream
    Feb 14, 2013 at 15:53

You must log in to answer this question.

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