0

I have one scenario where I need to change value of Date in swift while doing XCUITest.

I mean if current date returns 2022/07/06 22:31, I just want it should use some different time while running UI test cases say 2022/07/06 24:31

Example:

let date = Date()
myLabel.text = date // 2022/07/06 22:31

While running UI test cases, if I swizzle Date and replace it with some other date by adding 2 hours.



So while executing UI test case, 
myLabel.text = date // 2022/07/06 24:31
PJR
  • 13,052
  • 13
  • 64
  • 104
  • 1
    The Apple documentation provides functions for incrementing and decrementing Dates. https://developer.apple.com/documentation/foundation/date – Mike Collins Jul 07 '22 at 18:56
  • 1
    Date is a struct; it cannot be swizzled. Change your code to accept a Date that is passed (it can default to `Date()` is you like), and pass the date rather than calling `Date()` internally. (The main lesson is that you will need to restructure your code to assist in the testing; you won't be able to just reach in and monkeypatch the code to do random things.) – Rob Napier Jul 07 '22 at 20:55
  • Thanks @RobNapier. And If I swizzle NSDate it will not work with my swift code right ? Because in my swift code I used Date at all places. I know NSDate can be swizzled but it will not make any impact on Date. – PJR Jul 08 '22 at 05:08
  • Correct. Although I wouldn't be surprised if it's impossible to swizzle NSDate, even in ObjC. I haven't dug into it, but NSDate is toll-free bridged to CFDate, and you generally can't swizzle CF objects. Swizzling objects you don't control is extremely fragile. I'd be hesitant to even rely on it for tests. – Rob Napier Jul 08 '22 at 12:35
  • @PJR Your code is missing the concept of a `Clock`. Every place where you access `Date()`, you have an implicit dependency on the system time. Now you're trying to find a way to hack the system time to be different, and that's going to be hard. Instead, if you just made the time an explicit parameter (or a Clock that you can read the time from), then your tests could provide a fake time or a fake clock that vends fake times. – Alexander Jul 09 '22 at 02:25
  • Yes @Alexander, Issue is code is already written. Now I am focusing on UI automation. – PJR Jul 14 '22 at 11:25
  • @pjr lucky for you, software is *soft*, and easy to change (that,s the whole point). It’s not like there’s thousands of printed circuit boards or silicon chips that you messed up that are ruined forever – Alexander Jul 14 '22 at 12:34

0 Answers0