【问题标题】:Swift extensions and Unit TestsSwift 扩展和单元测试
【发布时间】:2018-01-08 10:56:05
【问题描述】:

我在尝试用 swift 编写一些 UT 时遇到问题

我有一个扩展名为“做事”的协议:

protocol MyProtocol: class
{
    var myVar: SomeClass { get }

    func doStuff(identifier: String) -> Bool
}

extension MyProtocol
{
    func doStuff(identifier: String) -> Bool {
        return true
    }
}

然后是一个实现我的协议的类

final class MyClass: MyProtocol {

}

这个类有一个扩展,它实现了另一个协议,它有一个我应该测试的方法

public protocol MyOtherProtocol: class {
    func methodToTest() -> Bool
}

extension MyClass: MyOtherProtocol {
    public func methodToTest() {
        if doStuff() {
            return doSomething()
        }

    }
}

这种设置有没有办法模拟 doStuff 方法?

【问题讨论】:

    标签: swift unit-testing swift-protocols


    【解决方案1】:

    解决协议而不是类是一种很好的做法。因此,您可以扩展协议而不是扩展您的课程

    extension MyOtherProtocol where Self: MyProtocol {
        public func methodToTest() {
            if doStuff() {
                return doSomething()
            }
    
        }
    }
    

    所以您的扩展程序会知道 doStuff 存在,但不知道它的实现。然后让你的类符合两者。

    extension MyClass: MyOtherProtocol {}
    

    所以在模拟中你可以实现

    class MyMockClass: MyProtocol, MyOtherProtocol {
        func doStuff() -> Bool {
            return true
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-19
      • 1970-01-01
      • 2013-05-08
      • 2019-08-18
      • 2020-07-12
      • 1970-01-01
      相关资源
      最近更新 更多