ios - Swift 单元测试模拟类静态方法

标签 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()
}

当然这只是理论上的:(

最佳答案

也许是这样?

protocol AProto {
  static func myStaticMethod() -> BProto
}

class A: AProto {
  static func myStaticMethod() -> BProto {
    return B()
  }
}

class MockA: AProto {
  static func myStaticMethod() -> BProto {
    return MockB()
  }
}

protocol BProto {
  func getTitle() -> String
}

class B: BProto {
  func getTitle() -> String {
    return "hello"
  }
}

class MockB: BProto {
  func getTitle() -> String {
    return "bye bye"
  }
}

func someBoolFunc(_ aProto: AProto.Type = A.self) -> Bool {
  var b = aProto.myStaticMethod()
  if (b.getTitle() == "hello") {
    return true
  }
  return false
}

print(someBoolFunc())
print(someBoolFunc(MockA.self))

关于ios - Swift 单元测试模拟类静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45372665/

相关文章:

Git - 在 $ git commit 之后无法运行 gpg

objective-c - 使用添加符号作为 NSImage

ios - @interface 和@implementation 指令中括号内的文本是什么意思?

iphone - EXC_BAD_ACCESS 在 setCollectionViewLayout 上

ios - 如何在最后一个 View Controller 上关闭三个 View Controller

ios - 了解隐藏在状态栏中的神奇数字

ios - CoreLocation 委托(delegate)函数在 View Controller viewDidLoad 函数完成之前不会运行

ios - 在 Swift 中为 UITextField 创建自定义输入

ios - App Tracking Transparency 如何影响显示广告的应用程序? - IDFA iOS14

macOS 命令无法访问 a.jar