gpt4 book ai didi

unit-testing - 在 Swift 中模拟

转载 作者:IT王子 更新时间:2023-10-29 04:59:25 25 4
gpt4 key购买 nike

如何在 Swift 中模拟一个对象?

Mirror 协议(protocol)听起来很有前途,但目前效果不佳。

到目前为止,我发现的唯一方法是子类化并覆盖模拟类的所有方法。这当然不是真正的模拟,远非理想,并且需要大量工作。

还有其他想法吗?

为什么不用 OCMock?

来自source :

Can I use OCMock using the language bridge functionality?

Yes, butwith limitations. If you are brave. As of now this is highlyexperimental. There's no guarantee that OCMock will ever fully supportSwift.

已知限制:

  • 测试必须用 Objective-C 编写
  • 应该模拟的对象必须继承自 NSObject
  • 没有 stub /期望/验证类方法

最佳答案

NSHipster触及 Swift 中的语言特性,这使得外部模拟库变得不太必要:

In Swift, classes can be declared within the definition of a function, allowing for mock objects to be extremely self-contained. Just declare a mock inner-class, override and [sic] necessary methods:

func testFetchRequestWithMockedManagedObjectContext() {
class MockNSManagedObjectContext: NSManagedObjectContext {
override func executeFetchRequest(request: NSFetchRequest!, error: AutoreleasingUnsafePointer<NSError?>) -> [AnyObject]! {
return [["name": "Johnny Appleseed", "email": "johnny@apple.com"]]
}
}

...
}

在本地范围内创建外部依赖项的子类的能力加上 XCTestExpectation 解决了很多与 OCMock 相同的问题。

OCMock 等库提供的非常有用的一件事是它的“验证”方法以确保调用模拟类。可以手动添加,但自动添加很好。

关于unit-testing - 在 Swift 中模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24174130/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com