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
grotibogrotibo 

Problem with multiple runAs()

Hello,

 

I have some problems in a testMethod when using 2 runAs(a User) with a User field modification between them.

 

Simplified example:

 

User u = new User(alias = 'test', email='testUser_1@test.com',
            emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='fr',
            localesidkey='fr_FR_EURO', profileid = 'xxxx',
            timezonesidkey='Europe/Paris', UserName='testUser_1@test.com');

System.runAs(u){
	System.assertEquals(Userinfo.getUserName(),'testUser_1@test.com');		//No problem here
}

u.UserName='testUser_2@test.com';		//I change the username

System.runAs(u){
	System.assertEquals(u.UserName,'testUser_2@test.com');				//No problem
	System.assertEquals(Userinfo.getUserName(),'testUser_2@test.com');		//Problem: Expected: testUser_1@test.com, Actual: testUser_2@test.com
}

 

And I have no problem if I omit the first runAs:

User u = new User(alias = 'test', email='testUser_1@test.com',
            emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='fr',
            localesidkey='fr_FR_EURO', profileid = 'xxxx',
            timezonesidkey='Europe/Paris', UserName='testUser_1@test.com');


u.UserName='testUser_2@test.com';		//I change the username

System.runAs(u){
	System.assertEquals(u.UserName,'testUser_2@test.com');				//No problem
	System.assertEquals(Userinfo.getUserName(),'testUser_2@test.com');		//No problem
}

 

Is that a bug from Apex?

Does someone has a solution to fix this problem? (other than creating another User object between the 2 runAs)

 

Thanks

 

 

Best Answer chosen by Admin (Salesforce Developers) 
grotibogrotibo

FYI if someone has already encountered this problem, I get a response from salesforce support and the bug fix is scheduled for Summer 12 release.

 

All Answers

spraetzspraetz

Hi grotibo,

 

This does appear to be a bug in Apex.  Thank you so much for reporting it.  In the meantime as a workaround you can simply initialize a new User variable and it should work.

 

Thanks again and sorry this impacted you.

grotibogrotibo

FYI if someone has already encountered this problem, I get a response from salesforce support and the bug fix is scheduled for Summer 12 release.

 

This was selected as the best answer