How to Swizzle Date (not NSDate) in Swift for XCUITest?
Asked Answered
V

0

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
Vmail answered 7/7, 2022 at 17:15 Comment(7)
The Apple documentation provides functions for incrementing and decrementing Dates. developer.apple.com/documentation/foundation/dateOkhotsk
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.)Reprieve
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.Vmail
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.Reprieve
@Vmail 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.Elwell
Yes @Alexander, Issue is code is already written. Now I am focusing on UI automation.Vmail
@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 foreverElwell

© 2022 - 2025 — McMap. All rights reserved.