【问题标题】:Nested function selector in swift for testing快速嵌套函数选择器进行测试
【发布时间】:2015-06-30 09:03:05
【问题描述】:

这是我的情况,也许有更简单的方法:

我正在测试一些使用通知的东西,我不想将我的期望定义为类级别的可选变量,所以我想知道我是否可以让它们成为函数的局部变量,这样我的通知处理程序可以访问它们。

我的尝试是将通知处理程序函数作为我的顶级测试函数中的嵌套函数 - 但我遇到了选择器命名问题,因为我不确定我需要告诉通知处理程序调用什么

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) 如何正确命名选择器以便找到它?

【问题讨论】:

    标签: swift testing xctest xctestexpectation


    【解决方案1】:

    问题是你是这么说的:

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

    但是 FilePlayerTests 类 self 没有名为 newHandler: 的选择器 - 因为您仅将该函数定义为 testFilePlayback 函数内的本地函数。它只存在于本地 - 只存在于 testFilePlayback 函数内部的代码眼中 - 并且只是非常临时的,即当 testFilePlayback 正在运行时。

    您必须在 FilePlayerTests 类的顶层定义newHandler:,以便它是通知中心可以实际调用的方法

    当然,这可能(即将)意味着您还必须将方法中的一些其他内容提升到顶级水平。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多