Swift中单元测试的静态函数依赖注入

时间:2018-05-09 11:12:37

标签: ios swift unit-testing dependency-injection

我知道这看起来像是一个常见的问题,但在阅读了10-15教程之后,我又想看看如何为我的服务类编写测试。我无法解决将静态函数移动到协议等等依赖注入的问题

我有一个如下图所示的网络层。我的所有函数类(如获取用户,新闻,媒体等)都调用“Service Caller”类,之后如果响应错误;调用“Service Error”类来处理错误,如果没有错误,则解码JSON。

我的问题是我将服务类称为静态函数,如“ServiceCaller.performRequest”,如果它出错,我也将错误类调用为静态,如“ServiceError.handle”。它还调用URLCache类来获取请求url的路径。我不确定如何让它们在测试类中进行依赖注入和模拟。正如我在教程中找到的那样,我应该写它;

protocol MyProtocol{
    func myfunction() -> Void
}
class A{
    let testProtocol = MyProtocol!
    init(pro: MyProtocol){
        testProtocol = pro
    }
}

并且在测试类的setup函数中它可能;

myMockProtocol = ...
myTestclass = A.init(pro: myMockProtocol)

How My Network layer works

但是我找不到如何使用ServiceCaller.performRequest或ServiceError.handle等静态调用。 (问题底部的简化版)

class AppInitService{

static func initAppRequest(_ completion: @escaping (_ appInitRecevingModel: Result<AppInitRecevingModel>) -> Void) {

    let sendingModel = AppInitSendingModel(cmsVersion: AppDefaults.instance.getCMSVersion())
    let route = ServiceRouter(method: .post, path: URLCache.instance.getServiceURL(key: URLKeys.initApp), parameters: (sendingModel.getJSONData()), timeoutSec: 1)
    ServiceCaller.performRequest(route: route) { (result) in
        if let error = result.error{
            if let statusCode = result.response?.statusCode{
                completion(.error(ServiceError.handle(error: error, statusCode: statusCode)))
            }else{
                completion(.error(ServiceError.handle(error: error, statusCode: error._code)))
            }
        }else{
            if let data = result.data{
                do{
                    var responseJson = JSON(data)
                    responseJson["idleTimeoutInMinutes"] = 10
                    let input = try AppInitRecevingModel(data: responseJson.rawData())
                    completion(.success(input))
                }catch let error{
                    completion(.error(ServiceError.handle(error: error, statusCode: -1002)))
                }
            }
        }}
}
 }

我的测试课程:

class MyProjectAppInitTests: XCTestCase {

var appInitTest: AppInitService!

override func setUp() {
    super.setUp()
    // Put setup code here. This method is called before the invocation of each test method in the class.
    appInitTest = AppInitService.init()
}

override func tearDown() {
    // Put teardown code here. This method is called after the invocation of each test method in the class.
    appInitTest = nil
    super.tearDown()
}

func testExample() {
    // This is an example of a functional test case.
    // Use XCTAssert and related functions to verify your tests produce the correct results.
    let testParamater = ["string":"test"]
    let route = ServiceRouter(method: .post, path: "/testPath", parameters: testParamater.getJSONData(), timeoutSec: 10)
    appInitTest. //cant call anything in here
}

教程我寻找单元测试;

https://www.raywenderlich.com/150073/ios-unit-testing-and-ui-testing-tutorial

https://www.swiftbysundell.com/posts/time-traveling-in-swift-unit-tests

https://marcosantadev.com/test-doubles-swift

http://merowing.info/2017/04/using-protocol-compositon-for-dependency-injection/

编辑:一种解决方案可能是为整个网络层和服务类编写init类,然后摆脱静态函数?但我不确定这是不是一个好方法。

编辑2:简化代码;

class A{

static func b(completion:...){
    let paramater = ObjectModel(somevariable: SomeClass.Singleton.getVariable()) //Data that I sent on network request
    let router = ServiceRouter(somevariable: SomeClassAgain.Singleton.getsomething()) //Router class which gets parameters, http method etc..

    NetworkClass.performNetworkRequest(sender: object2){ (result) in
        //Result - What I want to test (Write UnitTest about)
    }
}
}

1 个答案:

答案 0 :(得分:0)

Use mocking.

class ServiceCallerMock: ServiceCaller {
        override class func performRequest(route: ServiceRouter) -> (Any?) -> Void? {
            //your implementation goes here
        }
    }

You could mock ServiceCaller and override the performRequest method, then change the function to:

static func initAppRequest(_ completion: @escaping (_ appInitRecevingModel: Result<AppInitRecevingModel>) -> Void, serviceCaller: ServiceCaller.Type = ServiceCaller.self) {
    ...
    serviceCaller.performRequest(route: route) { (result) in
    ...
}

Then you could call the initAppRequest function using your mock implementation of ServiceCaller.