预期 0.0.2

Expectation 0.0.2

测试已测试
语言语言 SwiftSwift
许可证 MIT
发布日期最后发布日期2016年2月
SPM支持 SPM

Oliver Atkinson 维护。



  • Oliver Atkinson

Expectation

一个简单优雅的匹配器框架,基于 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) 如果 xy 使用 == 操作符相等则通过。

expect(x).to.beIdenticalTo(y) 比较 xy,如果它们具有相同的内存地址,则通过。

expect(x).to.beNil() 如果 xnil 则通过。

expect(x).to.beTrue() 如果 xtrue 则通过。

expect(x).to.beFalse() 如果 xfalse 则通过。

expect(x).to.contain(y) 如果数组 x 包含 y 则通过。

expect(x).to.haveCountOf(y) 如果数组 xy 个元素则通过。

expect(x).to.beEmpty(y) 如果数组 x 没有元素则通过。

expect(x).to.beDynamicType(y) 如果 x 有动态类型 y,则通过。可用于 classstruct

expect(x).to.beKindOfClass(y) 如果 x 是类 y 的实例,则通过。

expect(x).to.beCloseTo(y, within: z) 如果 xz 范围内接近 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) 如果字符串 xy 开头,则通过。

expect(x).to.haveSuffix(y) 如果字符串 xy 结尾,则通过。

* 目前仅适用于 NSObject,接受 Pull Requests 以添加仅对 Swift 类的功能。

反转断言器

可以通过在前面加上 .notTo 或 .toNot 来反转每个断言器的标准。

expect(x).toNot.equal(y) 比较 xy 并在它们不相等时通过。

强制失败

您可以使用 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))

自定义描述应与函数名称和值一起传递。

未来改进

  • [ ] 异步匹配
  • [ ] Swift 结构体和类的符合协议
  • [ ] 异常断言器
  • [ ] NSNotification 断言器
  • [ ] 为 Objective-C 也要这样做要做什么?

为功能请求创建问题.

替代方案

贡献

  1. 将其分支 (https://github.com/ollieatkinson/expectation/fork)
  2. 创建您的功能分支 (git checkout -b my-new-feature)
  3. 提交您的更改 (git commit -am 'Add some feature')
  4. 将更改推送到分支 (git push origin my-new-feature)
  5. 创建新的 Pull Request