一个简单优雅的匹配器框架,基于 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 = "")
有几个断言方法可用于
assertTrueassertFalseassertNilassertNotNilfail应该将这些用于验证函数的输入。
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)