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.

Does apex have a mechanism to designate a method to run before each testmethod?

Here is the JUnit annotation that I'm talking about: http://junit.sourceforge.net/javadoc/org/junit/Before.html

share|improve this question

1 Answer 1

up vote 5 down vote accepted

Apex doesn't provide these annotations, however, you can approximate @before code using a static block. For example:

public MyTestClass {
    static {
        //setup code here

    public static void TestOne() {
        // TestOne code

    public static void TestTwo() {
        // TestTwo code


Because each test runs in a separate execution context, the static block will run before each test method executes.

share|improve this answer
Thanks! That does exactly what I want it to. I didn't know that you can define an 'anonymous' static code block like that. –  edgartheunready Feb 10 '14 at 16:05

Your Answer


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.