我需要做一些测试,包括在几天内前后移动“电话”。我想在模拟器上做这个。是否有任何可用的 hack 允许更改在模拟器上看到的日期,而无需更改 Mac 日期?
4 回答
看起来这很困难......如何使用xcodebuild
从脚本自动构建和运行应用程序并使用systemsetup -setdate <mm:dd.yy>
在不同运行之间更改日期?那么你就不需要改变代码中的任何东西了。
您可以使用方法调配来替换[NSDate date]
运行时的实现以返回您选择的值。
有关方法调配的更多信息,请参阅http://www.icodeblog.com/2012/08/08/using-method-swizzling-to-help-with-test-driven-development/。
我需要自动测试我的应用程序,这需要更改系统时间。我做到了,正如汤姆建议的那样:快乐的 hacky 方法 swizzling。
出于演示目的,我只更改[NSDate date]
而不更改[NSDate dateWithTimeIntervalSince1970:]
。
首先你需要创建你的类方法作为新的[NSDate date]
. 我实现它只是为了简单地将时间移动一个常数timeDifference
。
int timeDifference = 60*60*24; //shift by one day
NSDate* (* original)(Class,SEL) = nil;
+(NSDate*)date{
NSDate* date = original([NSDate class], @selector(date));
return [date dateByAddingTimeInterval:timeDifference];
}
到目前为止,很容易。有趣的来了。我们从类和交换实现中获取方法(它在 AppDelegate 中对我有用,但在我的 UITests 类中不起作用)。为此,您需要导入objc/runtime.h
.
Method originalMethod = class_getClassMethod([NSDate class], @selector(date));
Method newMethod = class_getClassMethod([self class], @selector(date));
//save the implementation of NSDate to use it later
original = (NSDate* (*)(Class,SEL)) [NSDate methodForSelector:@selector(date)];
//happy swapping
method_exchangeImplementations(originalMethod, newMethod);
显然,请确保您在部署的应用程序中不使用这些。最后,我只能同意之前的答案,苹果为什么没有为此添加本机支持是非常值得怀疑的。
如果您正在创建应用程序,只需更改应用程序中的测试日期,您可以在发布时将其删除。