SwiftBlogiOS学习集--网上转载iOS开发实战

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

2016-03-10  本文已影响1215人  俞子将

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

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

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

现在很多开源库、开源项目,都加了单元测试,如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生命周期中的事件

手动触发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; // 测试提前返回
    }
    // 复杂操作...
}

参考资料

上一篇下一篇

猜你喜欢

热点阅读