使用OCMock测试NSWidowController

我一直试图想出一种方法来使用OCMock对applicationDidFinishLaunching委托进行单元测试。我的NSWindowController在这里实例化,我想测试它。这是我的测试代码:
id mockWindowController = [OCMockObject niceMockForClass:[URLTimerWindowController class]];
[[mockWindowController expect] showWindow:self];
NSUInteger preRetainCount = [mockWindowController retainCount];

[appDelegate applicationDidFinishLaunching:nil];

[mockWindowController verify];
当我运行测试时,我收到错误: “OCMockObject [URLTimerWindowController]:未调用预期方法:showWindow: - [URLTimerAppDelegateTests testApplicationDidFinishLaunching]” 日志提供了更多细节:
"Test Case '-[URLTimerAppDelegateTests testApplicationDidFinishLaunching]' started.
2011-04-11 08:36:57.558 otest-x86_64[3868:903] -[URLTimerWindowController loadWindow]: failed to load window nib file 'TimerWindow'.
Unknown.m:0: error: -[URLTimerAppDelegateTests testApplicationDidFinishLaunching] : OCMockObject[URLTimerWindowController]: expected method was not invoked: showWindow:-[URLTimerAppDelegateTests testApplicationDidFinishLaunching]
Test Case '-[URLTimerAppDelegateTests testApplicationDidFinishLaunching]' failed (0.005 seconds).
"
所以我看到NIB无法加载。好的,那么如何在单元测试时加载它或以某种方式模拟其负载呢?我已经看过OCMock文档,Chris Hanson关于单元测试的技巧和一些其他资源,包括WhereIsMyMac源代码,它们的行为方式类似。我实例化窗口控制器的应用程序是这样的:
self.urlTimerWindowController = [[URLTimerWindowController alloc] init];
[self.urlTimerWindowController showWindow:self];
任何提示非常感谢。     
已邀请:
测试的问题是
mockWindowController
urlTimerWindowController
不是同一个对象。你的考试中的
self
与被测班的
self
不同。在这种情况下,笔尖不会加载并不重要。 当您想要测试的方法中实例化对象时,通常无法模拟对象。一种替代方法是在一个方法中实例化对象,然后将其传递给另一个完成设置的方法。然后,您可以测试设置方法。例如:
-(void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    self.urlTimerWindowController = [[URLTimerWindowController alloc] init];
    [self setUpTimerWindow:urlTimerWindowController];
}

-(void)setUpTimerWindow:(URLTimerWindowController *)controller {
    [controller showWindow:self];
}
然后,你会测试
setUpTimerWindow:
-(void)testSetUpTimerWindowShouldShowWindow {
    URLTimerAppDelegate *appDelegate = [[URLTimerAppDelegate alloc] init];

    id mockWindowController = [OCMockObject niceMockForClass:[URLTimerWindowController class]];
    [[mockWindowController expect] showWindow:appDelegate]; // this seems weird. does showWindow really take the app delegate as a parameter?

    [appDelegate setUpTimerWindow:mockWindowController];

    [mockWindowController verify];
    [appDelegate release];
}
    

要回复问题请先登录注册