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
JBabuJBabu 

Question on class and test class data

Hi,

 

Iny my class I am querying on my existing data like below:

 

Line 1) user usersactual = [select Id from user where id =:userInfo.getUserId()];

 

and I will use "usersactual" record in my class as per my requirement.

 

In test class, as we shouldnot use any existing data. I have created a user as follows:

 


user  usertestdata = new User(alias = 'user1', userroleid = userroleRecord.Id, email='testinguser@test.com',
                                   emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US',
                                   localesidkey='en_US', profileid = profileRecord.Id, country='United States',
                                   timezonesidkey='America/New_York', username='testinguser@test.com')

 

My question for testing purpose as we want "usertestdata" (of test class) to be used as data in the main class (instead of the one mentioned above in Line 1 (usersactual) of the class).

How do we do this? Please help me on this.

 

 

Thanks.

JBabu.

Best Answer chosen by Admin (Salesforce Developers) 
ForceCoderForceCoder

You can use System.runAs:

 

System.runAs(usertestdata) {

YourClassUnderTest inst = new YourClassUnderTest();

         inst.yourMethodThatReferencesUserInfo();

}

 

 

All Answers

ForceCoderForceCoder

You can use System.runAs:

 

System.runAs(usertestdata) {

YourClassUnderTest inst = new YourClassUnderTest();

         inst.yourMethodThatReferencesUserInfo();

}

 

 

This was selected as the best answer
JBabuJBabu

Thanks a lot ForceCoder.