3

我正在尝试用布谷鸟快速模拟一项服务。这是服务中的原始功能:

typealias GetAppConfigCompletionHandler = (_ response: AppConfig) -> Void

func getAppConfig(delegate: ErrorCoordinatorDelegate,
                  retryClosure: (() -> Void)?,
                  response responseCallback: @escaping GetAppConfigCompletionHandler) {
    guard let appConfigUrl = "some/url"

    HttpClientService<AppConfig>.makeRequest(errorCoordinatorDelegate: delegate,
                                             retryClosure: retryClosure,
                                             url: appConfigUrl) { appConfig in
            responseCallback(appConfig)
        }
}

然后在测试中,我试图模拟 EndPointService 以使其回调我的模拟值而不是调用 API:

guard let mockedAppConfig: AppConfig = JsonTestingHelper.decodeJSON(resourceName: "mockAppConfig",
                                                                    model: AppConfig.self) else {
    fail("failed to create mockAppConfig from JSON")
    return
}

stub(endPointServiceMock) { mock in
    when(mock.getAppConfig(delegate: any(),
                           retryClosure: any(),
                           response: any())).then { callback in
        callback(mockedAppConfig) //error is here
    }
}

这就是生成的模拟函数的样子:

func getAppConfig(delegate: ErrorCoordinatorDelegate, retryClosure: (() -> Void)?, response responseCallback: @escaping GetAppConfigCompletionHandler)  {
    
return cuckoo_manager.call("getAppConfig(delegate: ErrorCoordinatorDelegate, retryClosure: (() -> Void)?, response: @escaping GetAppConfigCompletionHandler)",
        parameters: (delegate, retryClosure, responseCallback),
        escapingParameters: (delegate, retryClosure, responseCallback),
        superclassCall:
            
            Cuckoo.MockManager.crashOnProtocolSuperclassCall()
            ,
        defaultCall: __defaultImplStub!.getAppConfig(delegate: delegate, retryClosure: retryClosure, response: responseCallback))
    
}

从它看起来应该可以工作,但是我得到编译器在回调(mockedAppConfig)行抱怨:

不能调用非函数类型的值'(ErrorCoordinatorDelegate, (() -> Void)?, MockEndPointServiceType.GetAppConfigCompletionHandler)' (aka '(ErrorCoordinatorDelegate, Optional<(() -> ())>, (AppConfig) -> ( ))')

我错过了什么?

4

1 回答 1

2

错误消息虽然有点复杂,但可以准确地告诉您问题所在;

当您调用callback(mockedAppConfig)时,您的callback变量实际上是一个具有 3 个参数的元组(一个ErrorCoordinatorDelegate、一个可选Void函数和一个接受AppConfig参数的函数)。

为了修复此错误,您需要做的就是:

callback.2(mockedAppConfig)

(这是您引用元组的任何未命名参数的方式)

或者,更好的是,你可以让你的存根看起来像这样:

stub(endPointServiceMock) { mock in
    when(mock.getAppConfig(delegate: any(),
                           retryClosure: any(),
                           response: any())).then { _, _, callback in
        callback(mockedAppConfig)
    }
}

哪个更标准,更不晦涩:)

于 2022-01-06T13:25:18.257 回答