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


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.

  • 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

  • Nice find, this should definitely get accepted as the correct answer now that the feature is available. – Adrian Larson May 12 '15 at 22:03
  • 1
    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 '15 at 22:35
  • More nit-picking: this was GA in Spring '15, not Summer '15 ;) – kbentsen May 12 '15 at 22:35
  • @kbentsen - updated. Also, since this is SFSE you can always edit directly, or post a new answer :) – Benj May 13 '15 at 16:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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