一个简单优雅的匹配器框架,基于 XCTest 构建,用于 Swift。
这个框架有一些替代品,例如 Nimble,但是代码比较复杂,编写新的匹配器也很困难。
Expectation 通过协议扩展模式匹配为预期提供额外的方法。
Expectation 提供了易于使用的语法,无需指定数据类型。它也更容易阅读,且不遭受括号病的困扰。
expect("Mario").toNot.equal("Luigi")
expect(value).to.beNil()
expect(true).to.beTrue()
expect(index).to.beLessThanOrEqualTo(2, "index should be less than or equal to 2")
expect(NSURL(string: "http://google.com")).to.beKindOfClass(NSURL)
expect([ "Cow", "Sheep", "Dog" ]).to.contain("Cow")
expect(Double(1.2)).toNot.beCloseTo(1, within: 0.1)
expect(x).to.equal(y)
如果x
和y
使用==
操作符相等则通过。
expect(x).to.beIdenticalTo(y)
比较x
和y
,如果它们具有相同的内存地址,则通过。
expect(x).to.beNil()
如果x
是nil
则通过。
expect(x).to.beTrue()
如果x
是true
则通过。
expect(x).to.beFalse()
如果x
是false
则通过。
expect(x).to.contain(y)
如果数组x
包含y
则通过。
expect(x).to.haveCountOf(y)
如果数组x
有y
个元素则通过。
expect(x).to.beEmpty(y)
如果数组x
没有元素则通过。
expect(x).to.beDynamicType(y)
如果x
有动态类型y
,则通过。可用于class
和struct
。
expect(x).to.beKindOfClass(y)
如果x
是类y
的实例,则通过。
expect(x).to.beCloseTo(y, within: z)
如果x
在z
范围内接近y
,则通过。
expect(x).to.beLessThan(y)
如果x
小于y
,则通过。
expect(x).to.beLessThanOrEqualTo(y)
如果x
小于或等于y
,则通过。
expect(x).to.beGreaterThan(y)
如果x
大于y
,则通过。
expect(x).to.beGreaterThanOrEqualTo(y)
如果x
大于或等于y
,则通过。
expect(x).to.conformTo(y)
如果x
符合协议y
,则通过。 *
expect(x).to.respondTo(y)
如果x
符合协议y
,则通过。 *
expect(x).to.havePrefix(y)
如果字符串x
以y
开头,则通过。
expect(x).to.haveSuffix(y)
如果字符串x
以y
结尾,则通过。
* 目前仅适用于 NSObject,接受 Pull Requests 以添加仅对 Swift 类的功能。
可以通过在前面加上 .notTo 或 .toNot 来反转每个断言器的标准。
expect(x).toNot.equal(y)
比较x
和y
并在它们不相等时通过。
您可以使用 failure 属性来使测试失败。这可以用来测试分支。
fail("This should not happen")
使测试失败。
断言器简单且易于理解。
extension Expectation where T: Comparable {
func beLessThan(other: T, _ description: String = "") {
assertTrue(expect < other, self.description(__FUNCTION__, other, description))
}
}
包含方法所属类的模式是通过类扩展的断言器定义的。下面的例子是要匹配符合 Comparable 协议 的类型。
extension Expectation where T: Comparable
这里定义的函数只会对符合匹配模式的对象有效,在这种情况下是 Comparable
。
other
用于方法体以断言其真实性。description
是可选的,仅在您需要提供额外描述时才需要。func beLessThan(other: T, _ description: String = "")
有几个断言方法可用于
assertTrue
assertFalse
assertNil
assertNotNil
fail
应该将这些用于验证函数的输入。
assertTrue(expect < other, self.description(__FUNCTION__, other, description))
自定义描述应与函数名称和值一起传递。
…
git checkout -b my-new-feature
)git commit -am 'Add some feature'
)git push origin my-new-feature
)