I am writing a test class for testing an API, which populates the value of an iVAR with the logged in user's time zone. In real time, this API works fine. If the logged in User's time zone is EST, I get the value in EST (after formatting).
However, in the test class, I create a user with a Time zone of PST. Then I use the runAs api to execute code as the new user that I just created. However, the result is as per the logged in user's time zone (EST).
Any pointers would be greatly appreciated.
UPDATE:
Test Code
1. API to create a standard test user, refactored as this is used in multiple places.
public static User getTestUser(String profileName){
Profile pro = getTestUserProfile(profileName);
UserRole role = getUserRole(profileName.equals(System.Label.OperationUserProfile)
? Constants_TVNA.OPS_ROLENAME : Constants_TVNA.SALES_ROLENAME);
Long randomNumber = Math.mod (Math.mod (System.currentTimeMillis(), 1000000) , 989898989);
User myUser = new User(alias = 'ABS',
email='[email protected]',
emailencodingkey='UTF-8',
firstname='AB',
lastname='S',
languagelocalekey='en_US',
localesidkey='en_US',
profileId = pro.Id,
userRoleId = role.Id,
timezonesidkey='America/Los_Angeles',
username='unittestuser'+randomNumber+'@testorg.com',
RestrictRegion_TVNA__c = false,
isActive = true;
insert myUser;
return myUser;
}
2. Code that is being tested:
public with sharing class ClassBeingTested {
public String timeZoneShortString;
public ClassBeingTested() {
Time_Zone_Abbreviation_TVNA__mdt abbreviation = [Select DeveloperName from Time_Zone_Abbreviation_TVNA__mdt WHERE label = :(UserInfo.getTimeZone().getDisplayName())];
timeZoneShortString = abbreviation.DeveloperName ;
}
public String getTimeZoneShortString() {
return timeZoneShortString;
}
}
3. Testing Code: @isTest public class ClassBeingTested_Test {
static testMethod void orderPDFControllerTest()
{
System.RunAs(TestDataFactory_TVNA.getTestUser(System.Label.SalesUserProfile)){
ClassBeingTested cls = new ClassBeingTested();
System.assertEquals('PST', cls.timeZoneShortString);
}
}
The logged in user's time zone is EST. When the test case executes, the assert fails. Although when I make the logged in user's time zone as PST, the assert succeeds.