Swift单元测试mock类静态方法

时间:2017-07-28 11:43:59

标签: ios swift macos unit-testing

我在类

中有一个静态方法
class A {
    static func myStaticMethod() -> B {
        return B()
    }
}

class B {
    func getTitle() -> String {
        // some functionality here
    }
}

在我想要测试的类方法中,我使用它:

func someBoolFunc() -> Bool {
    var b = A.myStaticMethod()
    if (b.getTitle() = “hello”) {
         return true
    }
    return false
}

如何为此编写模拟类...我试过:

class MockA: A {
    var myTitle:String
    // this seems incorrect, because i didn't override static function
    func myStaticMethod() -> MockB {
        var b = MockB()
        b.title = myTitle
        return b
    }
}

class MockB: B {
    var myTitle:String    

    func getTitle() -> String {

        return myTitle
    }
}

在测试中我想使用类似的东西:

func testExample() {
    A = MockA
    MockA.title = "My title"
    // And now this func should use my MockA instead of A
    someBoolFunc()
}

但当然只是在理论上:(

1 个答案:

答案 0 :(得分:11)

也许这样?

{{1}}