我正在寻找一种“最佳实践”/“低测试摩擦”方法来对我的基本 AppDelegate 类中的 View Controller 进行基于状态的测试。目前,当类的方法内发生某些情况时,下面提供了一种简单的方法来在我自己的 UIViewController 中进行 stub (使用 ocmock)。
-(FirstViewController *)getFirstViewController
{
if (self.viewController1)
{ return self.viewController1; }
self.viewController1 = [[FirstViewController alloc] initWithNibName:@"FirstViewController" bundle:nil];
return self.viewController1;
}
我的第一个问题 - 这是 stub /注入(inject)我自己的模拟 View Controller 进行测试的有效方法吗? (似乎效果很好,但我不确定这是否是专业人士今天进行基于状态的测试的方式)
我的下一个问题 - 像这样在内存中保留 1 个 View Controller 副本是否有效(在应用程序的生命周期中仅从头开始创建一次)?
**注意-我会依赖注入(inject)这个,但我的 init 已经足够大了,只需注入(inject)导航 Controller 和选项卡栏 Controller ,因此遗憾的是,这不是这个大类的选项
最佳答案
如果它是 Root View Controller ,您应该将其作为应用程序委托(delegate)的属性:
@interface MyAppDelegate : NSObject <UIApplicationDelegate>
@property(retain)FirstViewController *firstViewController;
@end
@implementation MyAppDelegate
@synthesize firstViewController;
...
@end
除非您正在测试的方法是初始化 firstViewController
的方法,否则您不需要任何类型的延迟加载方法。您只需在测试中获取应用程序委托(delegate),创建 FirstViewController 的实例并将其分配给委托(delegate)上的属性,然后定义测试:
-(void)testSomething {
MyAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
FirstViewController *firstViewController = [[FirstViewController alloc] init];
appDelegate.firstViewController = firstViewController;
// test some app delegate method
...
}
如果您想为您正在测试的任何内容模拟 Controller ,您也可以这样做:
-(void)testSomething {
MyAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
id mockController = [OCMockObject mockForClass:[FirstViewController class]];
appDelegate.firstViewController = mockController;
[[mockController expect] someControllerMethod];
// test some app delegate method
...
[mockController verify];
}
关于objective-c - 如何在 iOS 5 运行时上 stub /注入(inject) View Controller 以进行基于状态的测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9753505/