Sign up ×
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:

share|improve this question

2 Answers 2

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

The Spring '15 Release adds support for an @testSetup method, which runs before testmethods defined in the class.

Use test setup methods (methods that are annotated with @testSetup) to create test records once and then access them in any test method in the test class. Test setup methods are useful and can be time-saving when you need to create a common set of records that all test methods operate on or prerequisite data.

You asked about a way to run a method "before each testmethod", and technically, this solution runs just once, before all of the testmethods in the class. However, documentation explains that after each testmethod, the test runner rolls back all database updates made during the previous method -- so this new annotation has the effect of running for each testmethod.

Read more: Release Notes

share|improve this answer
Nice find, this should definitely get accepted as the correct answer now that the feature is available. – Adrian Larson May 12 at 22:03
It may be worth pointing out that the OP's original ask is for "a method to run before each testmethod" and while @testSetup may solve what he was trying to do, to my understanding, it is not actually executed before each test method. It executes only once before everything else, and then the data that is set up in it is rolled back to their initial values between each test method. I'm probably just being nit-picky on the semantics of the question but I feel it's worth mentioning :) – kbentsen May 12 at 22:35
More nit-picking: this was GA in Spring '15, not Summer '15 ;) – kbentsen May 12 at 22:35
@kbentsen - updated. Also, since this is SFSE you can always edit directly, or post a new answer :) – Benj May 13 at 16:19

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.