2015-04-22 154 views
0

這裏是我的情況,也許還有一個更簡單的方法來做到這一點:嵌套函數選擇用於測試

我測試使用的通知一些東西,我不希望有定義我的期望作爲類級別的可選變量,所以我想知道我是否可以通過我的通知處理程序可以訪問它們的方式使它們成爲函數的局部變量。

我的企圖是使通知處理函數作爲我頂層測試函數內部嵌套函數 - 但我碰到的選擇命名問題因爲我不知道我需要告訴通知處理程序調用

class FilePlayerTests: XCTestCase { 

func testFilePlayback() { 


    let f1URL : NSURL = NSBundle(forClass: FilePlayerTests.self).URLForResource("test1", withExtension: "csv")! 
    let f2URL : NSURL = NSBundle(forClass: FilePlayerTests.self).URLForResource("test2", withExtension: "csv")! 
    let f3URL : NSURL = NSBundle(forClass: FilePlayerTests.self).URLForResource("test3", withExtension: "csv")! 

    let f1 = dm.createFilePlayerFromURL(f1URL) 
    let f2 = dm.createFilePlayerFromURL(f2URL) 
    let f3 = dm.createFilePlayerFromURL(f3URL) 


    let e1 = expectationWithDescription("xplane1") 
    let e2 = expectationWithDescription("xplane2") 
    let e3 = expectationWithDescription("xplane3") 



    f1?.startPlayback() 


    //Define LocationMessage Observer 
    nc.addObserver(self, selector: "newHandler:", 
     name: dmNotification.LocationData.rawValue, 
     object: nil) 


    ///Prints out a new Location Message 
    func newHandler(notif: NSNotification) { 
     let msg = notif.asLocationMessage! 
     println(msg) 

     e1.fulfill() 
    } 

} 
} 

所以我的代碼崩潰,因爲它找不到選擇器。

1)這有效嗎?

2)我如何正確命名選擇器以便找到它?

回答

1

的問題是,你說這樣的:

nc.addObserver(self, selector: "newHandler:" ... 

self,將FilePlayerTests類,沒有選擇叫newHandler: - 因爲你已經定義了功能僅作爲testFilePlayback函數內的本地功能。它只存在於本地 - 只存在於testFilePlayback函數之後的代碼中 - 並且只是暫時存在,即testFilePlayback正在運行。

您必須在FilePlayerTests類的頂級定義newHandler:,以便通知中心實際可以調用的方法

這可能(也就是說)意味着當然也需要將方法中的其他內容提升到最高水平。