我能够通过调动应用程序委托设置器来模拟委托对象并验证某些期望,例如 applicationDidBecomeActive。
id<UIApplicationDelegate> delegate = [MyCustomDelegate alloc] init];
UIApplication *app = [UIApplication alloc] init];
app.delegate = delegate;
//results in "There can only be one UIApplication" error
反而:
@implementation AppDelegateTests {
- (void)testAppDelegate {
//perform swizzle on [UIApplication class] and method @selector(setDelegate:) with
//[self class] and at the bottom @selector(swizzledSetDelegate:)
id<UIApplicationDelegate> delegate = [MyCustomDelegate alloc] init];
//Here's the magic, this line actually calls [UIApplication setDelegate] and not the swizzledSetDelegate method below.
//If you don't understand this, look up how swizzling works and hopefully you can wrap your head around it. The logic is quite mind-bendy.
[self swizzledSetDelegate:delegate];
//here set up your mock on the delegate and verify state of things
}
- (void)swizzledSetDelegate:(id<UIApplicationDelegate>)delegate {
//do nothing
}
}
请注意,此示例对我需要测试的内容非常自定义,您需要考虑要模拟什么以及是否可能。