1

我一直在尝试想出一种方法来使用 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];

非常感谢任何提示。

4

1 回答 1

1

你的测试的问题是mockWindowControllerurlTimerWindowController不是同一个对象。并且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];
}
于 2011-04-12T17:40:53.553 回答