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

orad9167 7年前
   <p>swift在iOS开发中越来越普及,大家都认同swift将是iOS的未来,从objc切换到swift只是时间问题。但是,对于老的objc项目,特别是开发积累了2、3年的老项目,从objc转换到swift,基本上不太现实。</p>    <p>那么,如何在老项目中使用swift呢?我想起了单元测试。单元测试,完全是使用另外的target,只要正确配置,基本上不会影响到主target。所以,在单元测试中,我们可以大胆且开心地使用swift,hooray~~~</p>    <p>那么,为什么要写单元测试?有些人,可能觉得搞单元测试,要花更多的时间,写更多的代码,感觉不划算。但是,单元测试也有如下一些优点:</p>    <ul>     <li>使你自己更自信。</li>     <li>代码不会退化。你不会因为修改了一个bug,而导致另外的bug。</li>     <li>有良好的单元测试,可以进行大胆的重构了。</li>     <li>良好的单元测试,本身就是使用说明,有时比文档更有用。</li>    </ul>    <p>现在很多开源库、开源项目,都加了单元测试,如AFNetworking的swift版本,Alamofire,就写了大量的测试代码:</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/9450379f5377cf84e2e4fd2e917d22f7.png"></p>    <p>较复杂的开源项目,如firefox-ios,也会写一些测试代码:</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/286d7c4ce614e547afaf0bd2ada44175.png"></p>    <p>可以认为没有单元测试的开源项目,都是在耍流氓,:)</p>    <h2>单元测试中的基本概念</h2>    <h3>TDD</h3>    <p>TDD(Test Drive Development),指的是测试驱动开发。我们一般的想法是先写产品代码,而后再为其编写测试代码。而TDD的思想,却是先写测试代码,然后再编写相应的产品代码。</p>    <p>TDD中一般遵从red,green,refactor的步骤。因为,先编写了测试代码,而还未添加产品代码,所以编译器会给出红色报警。而后,你把相应的产品代码添加上后,并让它通过测试,此时就是绿色状态。如此反复直到各种边界和测试都进行完毕,此时我们就可以得到一个很稳定的产品。因为产品都有相关的测试代码,所以我们可以大胆进行重构,只要保证项目最后是绿色状态,就说明重构不会有问题。</p>    <p>TDD的过程,有点像脚本语言的交互式编程,你敲几行代码,就可以检查下结果,如果结果不对,则要把最近的代码进行重写,直到结果正确为止。</p>    <h3>BDD</h3>    <p>BDD(Behavior Drive Development),行为驱动开发。它是敏捷中使用的测试方法,它提倡使用Given...When...Then这种类似自然语言的描述来写测试代码。如,Alamofire中下载的测试:</p>    <pre>  <code class="language-swift">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")  }</code></pre>    <h3>Mock</h3>    <p>Mock让你可以检查某种情况下,一个方法是否被调用,或者一个属性是否被正确设值。比如,viewDidLoad()后,某些属性是否被设值。</p>    <p>objc下可以使用OCMock来mock对象。但是,由于swift的runtime比较弱,所以,swift上一般要手动写mock。</p>    <h3>Stub</h3>    <p>如果你跟别人协同开发时,别人的模块还没有完成,而你需要用到别人的模块,这时,就要用到Stub。比如,后端的接口未完成,而你的代码已经完成了。Stub可以伪造了一个调用的返回。</p>    <p>ojbc下可以使用OHHTTPStubs来伪造网络的数据返回。swift下,仍要手动写stub。</p>    <h2>使用Quick+Nimble实现BDD</h2>    <h3>为什么使用Quick</h3>    <p>上面Alamofire的例子中,它使用的是苹果的XCTest,所以你会看到它会写很长的函数名,每个Assert,后面还要写很长的注释。</p>    <p>而Quick库,写起来是这样子的:</p>    <p><img src="https://simg.open-open.com/show/64c9bc260ceff554cf8b7bfb73173828.png"></p>    <p>它更符合BDD的思想,再配合Nimble这个expect库,出错提示也不用写,它自动生成的错误提示已经很可读了。</p>    <p>另外,相比于其他BDD库,它是纯swift写的,可以更方便地用来测试objc代码、swift代码。</p>    <p>注:目前也有很多开源项目,把测试从第三方BDD库换回到XCTest了,可能更看重XCTest的原生性,所以测试库的选择还是看个人了。</p>    <h3>使用Cocoapods导入库</h3>    <p>我们要使用Quick和Nimble库,可以使用Cocoapods进行管理。在Podfile中添加如下代码:</p>    <pre>  <code class="language-swift">use_frameworks!    def testing_pods      pod 'Quick', '~> 0.9.0'      pod 'Nimble', '3.0.0'  end    target 'MyTests' do      testing_pods  end</code></pre>    <p>注: swift库在Podfile中,必须使用 use_frameworks! 。但是,Cocoapods在这种情况下,会把所有的其他库也变成Frameworks动态库的方式。如果,你为了兼容,仍需要使用.a的静态库,则发布时,记得要注释掉该行。</p>    <h3>Quick使用</h3>    <p>Quick的使用很简单,基本上上面的那张图已经可以涵盖了。基本上类似如下:</p>    <pre>  <code class="language-swift">describe("a dolphin") {    describe("its click") {      context("when the dolphin is near something interesting") {        it("is emitted three times") {          // expect...        }      }    }  }</code></pre>    <p>另外,对每个group,可以添加beforeEach和afterEach,来进行setup和teardown(还是可以看上面那张图中的例子)。</p>    <h3>使用Nimble进行expect</h3>    <p>Quick中的框架看起来很简单。稍微麻烦的是expect的写法。这部分是由Nimble库完成的。</p>    <p>Nimble一般使用 expect(...).to 和 expect(...).notTo 的写法,如:</p>    <pre>  <code class="language-swift">expect(seagull.squawk).to(equal("Oh, hello there!"))  expect(seagull.squawk).notTo(equal("Oh, hello there!"))</code></pre>    <p>Nimble还支持异步测试,简单如下这样写:</p>    <pre>  <code class="language-swift">dispatch_async(dispatch_get_main_queue()) {    ocean.add("dolphins")    ocean.add("whales")  }  expect(ocean).toEventually(contain("dolphins"), timeout: 3)</code></pre>    <p>你也可以使用waitUntil来进行等待。</p>    <pre>  <code class="language-swift">waitUntil { done in    // do some stuff that takes a while...    NSThread.sleepForTimeInterval(0.5)    done()  }</code></pre>    <p>下面详细列举Nimble中的匹配函数。</p>    <ul>     <li>等值判断</li>    </ul>    <p>使用equal函数。如:</p>    <pre>  <code class="language-swift">expect(actual).to(equal(expected))  expect(actual) == expected  expect(actual) != expected</code></pre>    <ul>     <li>是否同一个对象</li>    </ul>    <p>使用beIdenticalTo函数</p>    <pre>  <code class="language-swift">expect(actual).to(beIdenticalTo(expected))  expect(actual) === expected  expect(actual) !== expected</code></pre>    <ul>     <li>比较</li>    </ul>    <pre>  <code class="language-swift">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</code></pre>    <p>比较浮点数时,可以使用下面的方式:</p>    <pre>  <code class="language-swift">expect(10.01).to(beCloseTo(10, within: 0.1))</code></pre>    <ul>     <li>类型检查</li>    </ul>    <pre>  <code class="language-swift">expect(instance).to(beAnInstanceOf(aClass))  expect(instance).to(beAKindOf(aClass))</code></pre>    <ul>     <li>是否为真</li>    </ul>    <pre>  <code class="language-swift">// 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())</code></pre>    <ul>     <li>是否有异常</li>    </ul>    <pre>  <code class="language-swift">// 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"))  })</code></pre>    <ul>     <li>集合关系</li>    </ul>    <pre>  <code class="language-swift">// 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())</code></pre>    <ul>     <li>字符串</li>    </ul>    <pre>  <code class="language-swift">// 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))</code></pre>    <ul>     <li>检查集合中的所有元素是否符合条件</li>    </ul>    <pre>  <code class="language-swift">// 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)))</code></pre>    <ul>     <li>检查集合个数</li>    </ul>    <pre>  <code class="language-swift">expect(actual).to(haveCount(expected))</code></pre>    <ul>     <li>匹配任意一种检查</li>    </ul>    <pre>  <code class="language-swift">// 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))</code></pre>    <h3>测试UIViewController</h3>    <p>触发UIViewController生命周期中的事件</p>    <ul>     <li>调用 UIViewController.view, 它会触发 UIViewController.viewDidLoad()。</li>     <li>调用 UIViewController.beginAppearanceTransition() 来触发大部分事件。</li>     <li>直接调用生命周期中的函数</li>    </ul>    <p>手动触发UIControl Events</p>    <pre>  <code class="language-swift">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"))    }  }</code></pre>    <h2>例子</h2>    <p>例子使用 <a href="/misc/goto?guid=4959736379033798941" rel="nofollow,noindex">参考资料5</a> 中的例子。我们使用Quick来重写测试代码。</p>    <p>这是一个简单的示例,用户点击右上角+号,并从通讯录中,选择一个联系人,然后添加的联系人就会显示在列表中,同时保存到CoreData中。</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/99e4ae174b1305872f300d6fc3e3fc0c.png"></p>    <p>为了避免造成 Massive ViewController ,工程把tableView的DataSource方法都放到了PeopleListDataProvider这个单独的类中。这样做,也使测试变得更容易。在PeopleListViewController这个类中,当它选择了联系人后,会调用PeopleListDataProvider的addPerson,把数据加入到CoreData中,同时刷新界面。</p>    <p>为了测试addPerson是否被调用,我们要Mock一个DataProvider,它只含有最简化的代码,同时,在它的addPerson被调用后,设置一个标记addPersonGotCalled。代码如下:</p>    <pre>  <code class="language-swift">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() }  }</code></pre>    <p>接着,我们模拟添加一个联系人,看provider中方法是否被调用:</p>    <pre>  <code class="language-swift">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())      }  }</code></pre>    <p>上面只是一个简单地测试ViewController的例子。下面,我们也可以测试这个dataProvider。模拟调用provider的addPerson,则ViewController中的tableView应该会有数据,而且应该显示我们伪造的联系人。</p>    <pre>  <code class="language-swift">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"      }  }</code></pre>    <h2>补充</h2>    <h3>进行桥接</h3>    <p>因为使用swift去测objc的代码,所以需要桥接文件。如果项目比较大,依赖比较复杂,可以把所有的objc的头文件都导入桥接文件中。参考以下python脚本:</p>    <pre>  <code class="language-swift">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)</code></pre>    <h3>测试不依赖主target</h3>    <p>默认运行unit test时,产品的target也会跟着跑,如果应用启动时做了太多事情,就不好测试了。因为测试的target和产品的target都有Info.plist文件,可以修改测试中的Info.plist的bundle name为 UnitTest ,然后在应用启动时进行下判断。</p>    <pre>  <code class="language-swift">- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {      NSString *value = [[[NSBundle mainBundle] infoDictionary] valueForKey:@"CFBundleName"];      if ([value isEqualToString:@"UnitTest"]) {          return YES; // 测试提前返回      }      // 复杂操作...  }</code></pre>    <h2>参考资料</h2>    <ul>     <li><a href="/misc/goto?guid=4959736379126259078" rel="nofollow,noindex">1. Quick github</a></li>     <li><a href="/misc/goto?guid=4959629859297039907" rel="nofollow,noindex">2. Nimble github</a></li>     <li><a href="/misc/goto?guid=4959736379229856233" rel="nofollow,noindex">3. TDD的iOS开发初步以及Kiwi使用入门</a></li>     <li><a href="/misc/goto?guid=4959736379319104082" rel="nofollow,noindex">4. Kiwi 使用进阶 Mock, Stub, 参数捕获和异步测试</a></li>     <li><a href="/misc/goto?guid=4959736379033798941" rel="nofollow,noindex">5. Unit Testing Tutorial: Mocking Objects</a></li>    </ul>    <p> </p>    <p>来自:http://www.jianshu.com/p/f13fc6aed467</p>    <p> </p>