+ Start a Discussion

Test Class order of execution of static block?

Hi.... below is the code for a test class I am writing. What I see is that, the static block is being called TWICE instead of once, once ecah time at the beginning of execution of both my test methods. Can anyone plz point out why is his so? i.e. since it is static, it should be loaded only one, when the class itself is loaded isnt it?


public class SomeTest {
    static someVar=null;
    static {
    static testMethod void method1Test(){
    static testMethod void method2Test(){
    public static void prepareTestUserData() {
        System.debug('I am called');
        //initialization code for someVar


many thanks


This is as designed. Each test runs in its own execution context (transaction), so all data is unloaded between each test.

Agreed with the fox. Your test data is torn down automatically at the end of each test method, so setting it up in the static block will not work. 


You have the right idea, static test factory method. But you need to call it at the beginning of each test method. 

For setting up data for my test classes. I have tried both the approaches
1> Creating setup data in static block
2> Creating setup data in static test method and calling it from each method.
Both approaches are working for me.
I want to understand which one is more efficient.
The time takem to run the test class in parallel execution is nearly same in both approaches.
I have observed this in my one test class having 10 test methods.
In approach2> the setup data testmethod time is also added in logs. For 1> it will not show in logs.

So by using which approach parallel test execution will be more faster and efficient. Can you please suggest. I want to apply that  to all the test classes.