【问题标题】:Methods in Default Protocol extension executed on unit testing always默认协议扩展中的方法总是在单元测试中执行
【发布时间】:2020-03-23 13:51:02
【问题描述】:

我有一个协议,该协议在该协议的扩展中具有默认实现。当我尝试创建该协议的具体模拟对象以进行单元测试时,总是会执行默认实现。我不知道为什么。任何帮助,将不胜感激。我在 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 调度,但找不到任何特殊原因。请帮忙。

【问题讨论】:

  • 它在我这边工作,调用了模拟方法。也许您在原始代码中有错字导致您注意到的行为?

标签: ios swift unit-testing


【解决方案1】:

你需要注入协议。

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")
    }
}

这个sn-p的代码很简单,但是根据你的问题,这是最好的方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    相关资源
    最近更新 更多