function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
msreekmmsreekm 

test methods- initializing and sharing data between test methods

public with sharing class MyTest {
   static string mynum='10';
    private MyTest()    {
       mynum='11112222';
    }      
 static testMethod void testMethod1() {
   System.Debug('value of mynum >>>>>>>' + MyTest.mynum);  -- prints 10
    } 
 static testMethod void testMethod2() {           
       mynum='1111';
       System.Debug('value of mynum  >>>>>>>' + MyTest.mynum);  --prints  1111
  }
}

 

I observed that test method 2 execute first and then test method 1. Is there a good way to init common data across methods. MyTest() constructor doesnt work . Also value set in one method is not retained in the next method..

WesNolte__cWesNolte__c

Hey

 

Test methods are static so they aren't 'attached' to an instance of a class. They are also a bit special, as they are picked up when you choose to 'Run Tests'(probably using the 'testmethod' keyword).

 

I don't think there is a way for test methods to share data, as that might goes against the concept of a unit test, but what I do use are common initialisation methods. As an example,

 

 static string mynum='10';

    private static void init()    {
       mynum='11112222';
    }    

 

  static testMethod void testMethod1() {

  init(); 

   System.Debug('value of mynum >>>>>>>' + MyTest.mynum);  -- will now print   11112222

 } 
 static testMethod void testMethod2() {           
       mynum='1111';
       System.Debug('value of mynum  >>>>>>>' + MyTest.mynum);  --prints  1111
  }
}

 

Cheers,

Wes