簡體   English   中英

使用OCMock測試NSWidowController

[英]Testing NSWidowController using OCMock

我一直在嘗試提出一種使用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];

任何提示,不勝感激。

測試的問題在於, 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];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM