使用swift给objc项目做单元测试

swift在iOS开发中越来越普及,大家都认同swift将是iOS的未来,从objc切换到swift只是时间问题。但是,对于老的objc项目,特别是开发积累了2、3年的老项目,从objc转换到swift,基本上不太现实。

那么,如何在老项目中使用swift呢?我想起了单元测试。单元测试,完全是使用另外的target,只要正确配置,基本上不会影响到主target。所以,在单元测试中,我们可以大胆且开心地使用swift,hooray~~~

那么,为什么要写单元测试?有些人,可能觉得搞单元测试,要花更多的时间,写更多的代码,感觉不划算。但是,单元测试也有如下一些优点:

  • 使你自己更自信。
  • 代码不会退化。你不会因为修改了一个bug,而导致另外的bug。
  • 有良好的单元测试,可以进行大胆的重构了。
  • 良好的单元测试,本身就是使用说明,有时比文档更有用。

现在很多开源库、开源项目,都加了单元测试,如AFNetworking的swift版本,Alamofire,就写了大量的测试代码:

较复杂的开源项目,如firefox-ios,也会写一些测试代码:


可以认为没有单元测试的开源项目,都是在耍流氓,:)

单元测试中的基本概念

TDD

TDD(Test Drive Development),指的是测试驱动开发。我们一般的想法是先写产品代码,而后再为其编写测试代码。而TDD的思想,却是先写测试代码,然后再编写相应的产品代码。

TDD中一般遵从red,green,refactor的步骤。因为,先编写了测试代码,而还未添加产品代码,所以编译器会给出红色报警。而后,你把相应的产品代码添加上后,并让它通过测试,此时就是绿色状态。如此反复直到各种边界和测试都进行完毕,此时我们就可以得到一个很稳定的产品。因为产品都有相关的测试代码,所以我们可以大胆进行重构,只要保证项目最后是绿色状态,就说明重构不会有问题。

TDD的过程,有点像脚本语言的交互式编程,你敲几行代码,就可以检查下结果,如果结果不对,则要把最近的代码进行重写,直到结果正确为止。

BDD

BDD(Behavior Drive Development),行为驱动开发。它是敏捷中使用的测试方法,它提倡使用Given...When...Then这种类似自然语言的描述来写测试代码。如,Alamofire中下载的测试:

func testDownloadClassMethodWithMethodURLHeadersAndDestination() {
    // Given
    let URLString = "https://httpbin.org/"
    let destination = Request.suggestedDownloadDestination(directory: searchPathDirectory, domain: searchPathDomain)

    // When
    let request = Alamofire.download(.GET, URLString, headers: ["Authorization": "123456"], destination: destination)

    // Then
    XCTAssertNotNil(request.request, "request should not be nil")
    XCTAssertEqual(request.request?.HTTPMethod ?? "", "GET", "request HTTP method should be GET")
    XCTAssertEqual(request.request?.URLString ?? "", URLString, "request URL string should be equal")

    let authorizationHeader = request.request?.valueForHTTPHeaderField("Authorization") ?? ""
    XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect")

    XCTAssertNil(request.response, "response should be nil")
}

Mock

Mock让你可以检查某种情况下,一个方法是否被调用,或者一个属性是否被正确设值。比如,viewDidLoad()后,某些属性是否被设值。

objc下可以使用OCMock来mock对象。但是,由于swift的runtime比较弱,所以,swift上一般要手动写mock。

Stub

如果你跟别人协同开发时,别人的模块还没有完成,而你需要用到别人的模块,这时,就要用到Stub。比如,后端的接口未完成,而你的代码已经完成了。Stub可以伪造了一个调用的返回。

ojbc下可以使用OHHTTPStubs来伪造网络的数据返回。swift下,仍要手动写stub。

使用Quick+Nimble实现BDD

为什么使用Quick

上面Alamofire的例子中,它使用的是苹果的XCTest,所以你会看到它会写很长的函数名,每个Assert,后面还要写很长的注释。

而Quick库,写起来是这样子的:


它更符合BDD的思想,再配合Nimble这个expect库,出错提示也不用写,它自动生成的错误提示已经很可读了。

另外,相比于其他BDD库,它是纯swift写的,可以更方便地用来测试objc代码、swift代码。

注:目前也有很多开源项目,把测试从第三方BDD库换回到XCTest了,可能更看重XCTest的原生性,所以测试库的选择还是看个人了。

使用Cocoapods导入库

我们要使用Quick和Nimble库,可以使用Cocoapods进行管理。在Podfile中添加如下代码:

use_frameworks!

def testing_pods
    pod 'Quick', '~> 0.9.0'
    pod 'Nimble', '3.0.0'
end

target 'MyTests' do
    testing_pods
end

注: swift库在Podfile中,必须使用 use_frameworks!。但是,Cocoapods在这种情况下,会把所有的其他库也变成Frameworks动态库的方式。如果,你为了兼容,仍需要使用.a的静态库,则发布时,记得要注释掉该行。

Quick使用

Quick的使用很简单,基本上上面的那张图已经可以涵盖了。基本上类似如下:

describe("a dolphin") {
  describe("its click") {
    context("when the dolphin is near something interesting") {
      it("is emitted three times") {
        // expect...
      }
    }
  }
}

另外,对每个group,可以添加beforeEach和afterEach,来进行setup和teardown(还是可以看上面那张图中的例子)。

使用Nimble进行expect

Quick中的框架看起来很简单。稍微麻烦的是expect的写法。这部分是由Nimble库完成的。

Nimble一般使用 expect(...).toexpect(...).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 "\n".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; // 测试提前返回
    }
    // 复杂操作...
}

参考资料

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,612评论 4 59
  • 出国部
    dddfrog阅读 255评论 0 0
  • 智能商业双螺旋:制造大公司 随着腾讯和阿里巴巴先后突破3000亿美金的市值,全世界前十大企业里面已经有五家是纯互联...
    妘如雪阅读 483评论 0 1
  • 今天回了老家一趟,回了家之后,和邻居聊聊,今年因为天旱,老百姓的日子不好过,东西都不值钱。谈了比较多,老百姓...
    吕诺爸阅读 127评论 0 3
  • 外甥女问我生活的家 我歪着脑袋,一心一意地说 屋顶很高,光线让人心里痒痒 从你家往这看仿佛是远山。 我住在阳光房里...
    倩何人换取阅读 297评论 0 1