swift2 在Swift中模拟XCTest

9cbw7uwe  于 2022-11-06  发布在  Swift
关注(0)|答案(1)|浏览(160)

我正在为我的项目编写测试用例,这是混合了Objective C和Swift代码。我知道OCMock框架,我以前用它来模拟/存根编写Objective C测试用例。但我在谷歌上搜索,发现它并不完全支持Swift。因为它是基于ObjectiveC运行时的。2我正在尝试用swift语言编写测试用例。3有没有方法可以对服务层进行模拟/存根。4例如:

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以便我可以编写测试用例?

p3rjfoxz

p3rjfoxz1#

您需要使用依赖注入才能模拟POST方法。
您的类(在其中定义了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
   }
}

在测试中,您使用mock初始化类:

let myClass = MyClass(requestManager: MockMyRequestManager())

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

相关问题