首页 > 解决方案 > 默认协议扩展中的方法总是在单元测试中执行

问题描述

我在该协议的扩展中有一个带有默认实现的协议。当我尝试创建该协议的具体模拟对象以进行单元测试时,总是会执行默认实现。我不知道为什么。任何帮助,将不胜感激。我在 xcode 11.3

protocol ABC: AnyObject {
 func doSomething()
}

extension ABC {
 func doSomething() {
   print("Did Something")
 }

}


final class ClassToBeTested {

    var abc: ABC?

    func methodToBeTested() {
       abc?.doSomething()
    }
}

在测试目标

final class MockABC: ABC {
   func doSomething() {
     print("Did Something in Test Target")
  }
}

final class Tests: XCTestCase {

   func testMethod() {
     let obj = ClassTobeTested()
     // abc property is of type protocol ABC
     obj.abc = MockABC()

    *This line calls the default implementation of the protocol of ABC and not the 
     implementation in MockABC class - verifiable by breakpoints and print statements*

     obj.methodToBeTested()

  }

}

我已经阅读了static在这种情况下发生的调度,但找不到任何特殊原因。请帮忙。

标签: iosswiftunit-testing

解决方案


您需要注入协议。

protocol ABC: AnyObject {
    func doSomething() -> String
}

extension ABC {
    func doSomething() -> String {
        return "Did Something"
    }
}

final class ClassToBeTested {

    private let abc: ABC

    init(abc: ABC) {
        self.abc = abc
    }

    func methodToBeTested() -> String {
       return abc.doSomething()
    }
}

测试目标

final class ABCMock: ABC {
    func doSomething() {
        print("Did Something in Test Target")
    }
}

final class ClassToBeTestedTests: XCTestCase {

    private let mockABC: MockABC = .init()

    func test_methodToBeTested() {
        let obj = ClassTobeTested()
        XCTAssertEqual(obj.methodToBeTested(), "Did Something in Test Target")
    }
}

这段代码非常简单,但根据您的问题,这是最好的方法。


推荐阅读