在 Swift 中模拟 XCTest

Mocking in Swift for XCTest

我正在为我的项目编写测试用例,它混合了 Objective C 和 Swift 代码。我知道 OCMock 框架,我之前曾在 mocking/Stubbing 中使用它来在 Objective C 中编写测试用例。 但我用谷歌搜索发现它不完全支持 swift,因为它基于 Objective C 运行时。 我正在尝试用 swift 语言编写测试用例。有什么办法可以为服务级别层做 mocking/Stubbing 吗?例如

 func getPersonData(id:String, success: (ReponseEnum) -> Void, failure: (error: NSError) -> Void) {


                let requestPara:NSDictionary =  ["id": id]

                let manager: MyRequestManager = MyRequestManager.sharedManager()

                //MyRequestManager is nothing but AFNetworking class 
                let jsonRequest
                /// Service request creation code here


                // Service Call

                manager.POST(url, parameters: jsonRequest, success: { (task: NSURLSessionDataTask!, responseObject: AnyObject!) -> () in

                    // Some business logic
                    //success block call
                    success (successEnum)



                }) {(task: NSURLSessionDataTask!, error: NSError!) -> () in

                    // failure block call
                    failure (failureEnum)

                }
    }

这里如何模拟 post 虚拟 responseObject 方法调用所以我可以编写测试用例?

您需要使用 依赖注入 才能模拟 POST 方法。

您的 class,您在其中定义了 getPersonData(id:success:failure) 方法,需要接受 MyRequestManager 作为构造函数中的参数:

class MyClass {
    private let requestManager: MyRequestManager

    init(requestManager: MyRequestManager) {
        self.requestManager = requestManager
    }
}

然后你为你的请求管理器创建一个模拟:

class MockMyRequestManager: MyRequestManager {

   // not sure about correct method signature
   override func POST(url: NSURL, parameters: [String: AnyObject], success: (() -> Void)?) {
       //implement any custom logic that you want to expect when executing test
   }
}

并且在测试中,您使用模拟初始化 class:

let myClass = MyClass(requestManager: MockMyRequestManager())

您可以在此处找到有关依赖注入的更多详细信息: http://martinfowler.com/articles/injection.html