1

I have a unit test that is passes when the user running the test is in the CST timezone, but in any other timezone, the unit test fails with the assertion error: Assertion Failed: Expected: 2014-05-19 13:00:00, Actual: 2014-05-19 14:00:00

Here is the test method:

static testMethod void testArtRequestSetDueDateStandard() {
    initialize(true);

    testArtRequest.Date_Time_Assigned__c = Datetime.newInstance(2014, 5, 17, 0, 0, 0);

    test.startTest();
        update testArtRequest;
    test.stopTest();

    Art_Request__c result = [select OwnerId, Status__c, Date_Time_Due__c from Art_Request__c where Id =: testArtRequest.Id];
    system.assertEquals(Datetime.newInstance(2014, 5, 19, 11, 0, 0), result.Date_Time_Due__c);
}

If needed, I can provide more of the actual code or full test code.

1

I would recommend using Datetime.newInstanceGmt instead, and also probably use relative data instead by calling addHours.

Datetime assigned = Datetime.newInstanceGmt(2014, 5, 17, 0, 0, 0, 0);
Datetime expectedDue = assigned.addHours(59);
1

Take a look at System.RunAs() method in apex .To avoid dependency of Test code on the running User ,its recommended to test the entire test code as a specific Test user using System.RunAs

@isTest
private class TestRunAs {
 public static testMethod void testRunAs() {
  // Setup test data
     // This code runs as the system user
      Profile p = [SELECT Id FROM Profile WHERE Name='Standard User']; 
      User u = new User(Alias = 'standt', Email='standarduser@testorg.com', 
      EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
  LocaleSidKey='en_US', ProfileId = p.Id, 
  TimeZoneSidKey='America/Chicago', UserName='standarduser@testorg.com');

  System.runAs(u) {
     // The following code runs as user 'u' 
     System.debug('Current User: ' + UserInfo.getUserName());
     System.debug('Current Profile: ' + UserInfo.getProfileId()); 
    //Now test your logic here
    }
  }
}
2
  • How does what you posted relate to time zones? It doesn't seem helpful relative to OP but maybe I am missing something. – Adrian Larson Feb 7 '16 at 1:31
  • The issue here i guess is there is some logic which has dependency on Timezone of user.Hence the proposal to test is to run as specific user rather than using deployment user .Hence if he could create user in CST timezone and use system.RunAs ,this will ensure test class always passes.Now I am not sure on business logic here but running system. RunAs will fix problems – Mohith Shrivastava Feb 7 '16 at 1:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.