Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

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?

share|improve this question
1  
    
@DanielBallinger Thanks for the heads-up! –  ipavlic Feb 18 '13 at 9:02

1 Answer 1

up vote 4 down vote accepted

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.

share|improve this answer
    
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 '13 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 '13 at 15:53
    
It happens :). I'm accepting the answer. Thank you. –  ipavlic Feb 14 '13 at 15:54

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.