测试已测试 | ✓ |
语种语言 | SwiftSwift |
许可证 | MIT |
发布最新版本 | 2017 年 8 月 |
SwiftSwift 版本 | 3.0 |
SPM支持 SPM | ✗ |
由 Stefanos Zachariadis 维护。
MCAssertReflectiveEqual 是一个可以用于编写 Swift 测试断言的函数。它非常类似于 XCTest 的 XCTAssertEqual,但不需要 Equatable 项,而是使用反射。因此,您无需编写生产代码中不需要的等价函数,也无需断言多个单个字段,使测试变得繁琐。
MCAssertReflectiveEquals 适用于原始数据类型、结构体、类和枚举。当项目不匹配时,它会提供友好的错误信息。它深入比较项目并处理递归循环(A -> B -> A,其中 A 和 B 是对象,-> 是引用)。它只是使测试变得更简单。
MCAssertReflectiveEqual 的开发描述请参阅 此处。
import XCTest
import MCAssertReflectiveEqual
private class ClassWithVal {
var val: Int
init(_ val: Int) {
self.val = val
}
}
class ClassWithValTest : XCTestCase {
func testAreEqual() {
let expected = ClassWithVal(1)
let actual = ClassWithVal(1)
MCAssertReflectiveEqual(expected, actual)
MCAssertReflectiveEqual([expected], [actual])
MCAssertReflectiveEqual(expected, ClassWithVal(5)) //fails
}
}
有时简单的反射匹配并不足够。设想一个包含地理坐标、CLLocation 的复杂数据结构。我们可能不感兴趣的是预期的值与正在测试的系统产生的值完全相同,我们只关心它们是否足够接近。以下是实现方法的示例
class FavouriteLocation {
let user: String
let location: CLLocation
init(user: String, location: CLLocation) {
self.user = user
self.location = location
}
}
let camdenTown = CLLocation(latitude: 51.5390, longitude: 0.1426)
let closeToCamdenTown = CLLocation(latitude: 51.5391, longitude: 0.1427)
let matcher = matcherFor(CLLocation.self, { (expected, actual) in
return expected.distance(from: actual) < 100 //close enough
})
MCAssertReflectiveEqual(FavouriteLocation(user: "bob", location: closeToCamdenTown),
FavouriteLocation(user: "bob", location: camdenTown),
matchers: [matcher])
为了方便起见,提供了一个具有定义精度的双精度浮点数断言。使用以下方式创建它
let accuracy = 0.001
let matcher = matchDoubles(withAccuracy: accuracy)
let expected = 0.01
let actual = 0.0101
MCAssertReflectiveEqual(expected, actual) //fails
MCAssertReflectiveEqual(expected, actual, matchers: [matcher]) //passes
更多示例请参阅 MCAssertReflectiveEqualTest.swift
MCAssertReflectiveEqual 通过 CocoaPods 提供。要安装它,只需将以下行添加到 Podfile 中。在测试目标中引用它是有意义的。
use_frameworks!
pod "MCAssertReflectiveEqual"
它在实际中仅由一个文件实现,因此如果您不想使用 CocoaPods,则应易于将其集成到项目中。
Stefanos Zachariadis,motocode ltd,firstName@lastName.net,https://moto.co.de
MCAssertReflectiveEqual 在 MIT 许可下提供。有关更多信息,请参阅 LICENSE 文件。