使用Nimble进行expect
  Quick中的框架看起来很简单。稍微麻烦的是expect的写法。这部分是由Nimble库完成的。
  Nimble一般使用 expect(...).to 和 expect(...).notTo的写法,如:
  expect(seagull.squawk).to(equal("Oh, hello there!"))
  expect(seagull.squawk).notTo(equal("Oh, hello there!"))
  Nimble还支持异步测试,简单如下这样写:
  dispatch_async(dispatch_get_main_queue()) {
  ocean.add("dolphins")
  ocean.add("whales")
  }
  expect(ocean).toEventually(contain("dolphins"), timeout: 3)
  你也可以使用waitUntil来进行等待。
  waitUntil { done in
  // do some stuff that takes a while...
  NSThread.sleepForTimeInterval(0.5)
  done()
  }
  下面详细列举Nimble中的匹配函数。
  等值判断
  使用equal函数。如:
  expect(actual).to(equal(expected))
  expect(actual) == expected
  expect(actual) != expected
  是否同一个对象
  使用beIdenticalTo函数
  expect(actual).to(beIdenticalTo(expected))
  expect(actual) === expected
  expect(actual) !== expected
  比较
  expect(actual).to(beLessThan(expected))
  expect(actual) < expected
  expect(actual).to(beLessThanOrEqualTo(expected))
  expect(actual) <= expected
  expect(actual).to(beGreaterThan(expected))
  expect(actual) > expected
  expect(actual).to(beGreaterThanOrEqualTo(expected))
  expect(actual) >= expected
  比较浮点数时,可以使用下面的方式:
  expect(10.01).to(beCloseTo(10, within: 0.1))
  类型检查
  expect(instance).to(beAnInstanceOf(aClass))
  expect(instance).to(beAKindOf(aClass))
  是否为真
  // Passes if actual is not nil, true, or an object with a boolean value of true:
  expect(actual).to(beTruthy())
  // Passes if actual is only true (not nil or an object conforming to BooleanType true):
  expect(actual).to(beTrue())
  // Passes if actual is nil, false, or an object with a boolean value of false:
  expect(actual).to(beFalsy())
  // Passes if actual is only false (not nil or an object conforming to BooleanType false):
  expect(actual).to(beFalse())
  // Passes if actual is nil:
  expect(actual).to(beNil())
  是否有异常
  // Passes if actual, when evaluated, raises an exception:
  expect(actual).to(raiseException())
  // Passes if actual raises an exception with the given name:
  expect(actual).to(raiseException(named: name))
  // Passes if actual raises an exception with the given name and reason:
  expect(actual).to(raiseException(named: name, reason: reason))
  // Passes if actual raises an exception and it passes expectations in the block
  // (in this case, if name begins with 'a r')
  expect { exception.raise() }.to(raiseException { (exception: NSException) in
  expect(exception.name).to(beginWith("a r"))
  })
  集合关系
  // Passes if all of the expected values are members of actual:
  expect(actual).to(contain(expected...))
  expect(["whale", "dolphin", "starfish"]).to(contain("dolphin", "starfish"))
  // Passes if actual is an empty collection (it contains no elements):
  expect(actual).to(beEmpty())
  字符串
  // Passes if actual contains substring expected:
  expect(actual).to(contain(expected))
  // Passes if actual begins with substring:
  expect(actual).to(beginWith(expected))
  // Passes if actual ends with substring:
  expect(actual).to(endWith(expected))
  // Passes if actual is an empty string, "":
  expect(actual).to(beEmpty())
  // Passes if actual matches the regular expression defined in expected:
  expect(actual).to(match(expected))
  检查集合中的所有元素是否符合条件
  // with a custom function:
  expect([1,2,3,4]).to(allPass({$0 < 5}))
  // with another matcher:
  expect([1,2,3,4]).to(allPass(beLessThan(5)))
  检查集合个数
  expect(actual).to(haveCount(expected))
  匹配任意一种检查
  // passes if actual is either less than 10 or greater than 20
  expect(actual).to(satisfyAnyOf(beLessThan(10), beGreaterThan(20)))
  // can include any number of matchers -- the following will pass
  expect(6).to(satisfyAnyOf(equal(2), equal(3), equal(4), equal(5), equal(6), equal(7)))
  // in Swift you also have the option to use the || operator to achieve a similar function
  expect(82).to(beLessThan(50) || beGreaterThan(80))
  测试UIViewController
  触发UIViewController生命周期中的事件
  · 调用 UIViewController.view, 它会触发 UIViewController.viewDidLoad()。
  · 调用 UIViewController.beginAppearanceTransition() 来触发大部分事件。
  · 直接调用生命周期中的函数
  手动触发UIControl Events
  describe("the 'more bananas' button") {
  it("increments the banana count label when tapped") {
  viewController.moreButton.sendActionsForControlEvents(
  UIControlEvents.TouchUpInside)
  expect(viewController.bananaCountLabel.text).to(equal("1"))
  }
  }
  例子
  例子使用 参考资料5中的例子。我们使用Quick来重写测试代码。
  这是一个简单的示例,用户点击右上角+号,并从通讯录中,选择一个联系人,然后添加的联系人会显示在列表中,同时保存到CoreData中。

  为了避免造成Massive ViewController,工程把tableView的DataSource方法都放到了PeopleListDataProvider这个单独的类中。这样做,也使测试变得更容易。在PeopleListViewController这个类中,当它选择了联系人后,会调用PeopleListDataProvider的addPerson,把数据加入到CoreData中,同时刷新界面。
  为了测试addPerson是否被调用,我们要Mock一个DataProvider,它只含有简化的代码,同时,在它的addPerson被调用后,设置一个标记addPersonGotCalled。代码如下:
  class MockDataProvider: NSObject, PeopleListDataProviderProtocol {
  var addPersonGotCalled = false
  var managedObjectContext: NSManagedObjectContext?
  weak var tableView: UITableView?
  func addPerson(personInfo: PersonInfo) { addPersonGotCalled = true }
  func fetch() { }
  func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 }
  func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { return UITableViewCell() }
  }
  接着,我们模拟添加一个联系人,看provider中方法是否被调用:
  context("add person") {
  it("provider should call addPerson") {
  let record: ABRecord = ABPersonCreate().takeRetainedValue()
  ABRecordSetValue(record, kABPersonFirstNameProperty, "TestFirstname", nil)
  ABRecordSetValue(record, kABPersonLastNameProperty, "TestLastname", nil)
  ABRecordSetValue(record, kABPersonBirthdayProperty, NSDate(), nil)
  viewController.peoplePickerNavigationController(ABPeoplePickerNavigationController(), didSelectPerson: record)
  expect(provider.addPersonGotCalled).to(beTruthy())
  }
  }
  上面只是一个简单地测试ViewController的例子。下面,我们也可以测试这个dataProvider。模拟调用provider的addPerson,则ViewController中的tableView应该会有数据,而且应该显示我们伪造的联系人。
context("add one person") {
beforeEach {
dataProvider.addPerson(testRecord)
}
it("section should be 1") {
expect(tableView.dataSource!.numberOfSectionsInTableView!(tableView)) == 1
}
it("row should be 1") {
expect(tableView.dataSource!.tableView(tableView, numberOfRowsInSection: 0)) == 1
}
it("cell show full name") {
let cell = tableView.dataSource!.tableView(tableView, cellForRowAtIndexPath: NSIndexPath(forRow: 0, inSection: 0)) as UITableViewCell
expect(cell.textLabel?.text) == "TestFirstName TestLastName"
}
}
  完整的测试代码,见demo。
  补充
  进行桥接
  因为使用swift去测objc的代码,所以需要桥接文件。如果项目比较大,依赖比较复杂,可以把所有的objc的头文件都导入桥接文件中。参考以下python脚本:
import os
excludeKey = ['Pod','SBJson','JsonKit']
def filterFunc(fileName):
for key in excludeKey:
if fileName.find(key) != -1:
return False
return True
def mapFunc(fileName):
return '#import "%s"' % os.path.basename(fileName)
fs = []
for root, dirs, files in os.walk("."):
for nf in [root+os.sep+f for f in files if f.find('.h')>0]:
fs.append(nf)
fs = filter(filterFunc, fs)
fs = map(mapFunc, fs)
print " ".join(fs)
  测试不依赖主target
  默认运行unit test时,产品的target也会跟着跑,如果应用启动时做了太多事情,不好测试了。因为测试的target和产品的target都有Info.plist文件,可以修改测试中的Info.plist的bundle name为UnitTest,然后在应用启动时进行下判断。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSString *value = [[[NSBundle mainBundle] infoDictionary] valueForKey:@"CFBundleName"];
if ([value isEqualToString:@"UnitTest"]) {
return YES; // 测试提前返回
}
// 复杂操作...
}