聊聊iOS&OSX测试相关的八卦

作者: 纸简书生 | 来源:发表于2016-11-16 15:05 被阅读187次

    说真的,自己在做客户端开发的时候基本没有写过单元测试。😁😁,不是对自己技术有多自信,而是因为基本忙不过来,加上上头没明确要求,就得过且过了。不过作为一个比较合格的攻城狮,对单元测试还是需要了解的。今天总结一下在开发iOS&OSX中从苹果自家的XCTest到牛的一比的第三方开源测试框架。由于东西多,一时半会弄不完,只做简单入门介绍。后续会一一介绍。

    从Xcode谈起

    苹果在Xcode5中推出了一个简单而有效的框架--XCTest用于做单元测试。XCTest是以xUnit way的方式写的。

    XCTest测试用例非常简单,而且开发者通过IDE点击⌘U可以非常迅速的获取Xcode的反馈信息。同时Xcode也有一个专门用户测试的区域,如下图,在这里我们可以看到所有的测试用例成功或者失败的情况。

    通过的测试用例用绿色标识,未通过的测试用例用红色标识。

    虽然XCTestXcode集成在一起非常方便,非常容易使用,但是也有一些问题,比如XCTAssert...API不是那么的有表现力和通用。尤其抛开了XcodeXCTest会比较麻烦。

    这里有篇介绍的不错的入门介绍:

    有精力的还是推荐看

    随着技术发展,为了更为方便的写UI测试。苹果t提供了UI测试框架--UIAutomation。UIAutomation通过JS来写测试,并且允许开发者驱动应用程序的UI并且在不同的状态插入断言。尽管这听说起来有点牛逼,但是真真的通过UIAutomation来写测试用例,结果会变得非常糟糕。并且JS的API没有原生的单元测试API强大。

    来看看JS写的:

    UIATarget.localTarget().frontMostApp().navigationBar().buttons()["Add"].tap();
    
    UIATarget.localTarget().frontMostApp().mainWindow().tableViews()[0].cells()[0].elements()["Chocolate Cake"];
    
    UIATarget.localTarget().frontMostApp().mainWindow().tableViews()[0].scrollToElementWithPredicate("name beginswith 'Turtle Pie'");
    

    正如你所见,麻蛋居然比我写OC的代码还冗长。并且必须使用Instruments来运行。总的来说就是不爽。苹果推出的最新的方案是Xcode Bot,举个例子,可以通过安装Xcode Server来自动跑测试用例。更加具体的内容可以看看看官方文档。

    以上是苹果自家的方案。

    测试相关的开源库

    关于iOS和OSX的开源项目还是有很多的。就单单来讲,收录到Cocoapods的项目而言。通过Pod list就可以知道有多少个了,我本机试了一下,一共有24173 pods were found。在这么多的第三方中,有一些非常不错的开发测试框架。

    单元测试的开源库大致都遵循了一种测试风格,事实上就是xSpec style,这种风格来至于Ruby测试库RSpec.提供了测试类更多的操作,而不仅仅只是枚举方法。

    Kiwi

    kiwi是一个行为驱动开发库,可以完全替代XCTest,语言用得是OC,所以开发上手也比较快。来看看具体怎么写:

    describe(@"Team", ^{
      context(@"when newly created", ^{
        it(@"has a name", ^{
          id team = [Team team];
          [[team.name should] equal:@"Black Hawks"];
        });
    
        it(@"has 11 players", ^{
          id team = [Team team];
          [[[team should] have:11] players];
        });
      });
    });
    

    Kiwi规范更容易阅读和沟通。而且在它的wiki里面写的非常详细。并且有自己的一套规范。有如下内容:

    • Specs:
    • Expectations:
    • Mocks and Stubs:
    • Asynchronous Testing:

    具体请看kiwi-bdd/Kiwi

    Specta

    specta是一个轻量级的TDD/BDD的测试框架,同样适用OC语言编写。相对于kiwi而言,kiwi更为庞大,specta更为轻量级、组件化。

    示例代码如下:

    SpecBegin(Thing)
    
    describe(@"Thing", ^{
      it(@"should do stuff", ^{
        // This is an example block. Place your assertions here.
      });
    
      it(@"should do some stuff asynchronously", ^{
        waitUntil(^(DoneCallback done) {
          // Async example blocks need to invoke done() callback.
          done();
        });
      });
    });
    

    specta有一些依赖的工具,可以根据需要添加。比如:

    target :MyApp do
    # your app dependencies
    
      target :MyAppTests do
        inherit! :search_paths
    
        pod 'Specta', '~> 1.0'
        # pod 'Expecta',     '~> 1.0'   # expecta matchers
        # pod 'OCMock',      '~> 2.2'   # OCMock
        # pod 'OCHamcrest',  '~> 3.0'   # hamcrest matchers
        # pod 'OCMockito',   '~> 1.0'   # OCMock
        # pod 'LRMocky',     '~> 0.9'   # LRMocky
      end
    end
    

    Quick

    quick相对而言比较年轻,适用Swift语言编写的,但是目前star数却高于前面介绍的框架。随便说一下,quick依赖一个匹配框架Nimble,弥补了XCTAssert()使用起来不够明确,清晰的缺点。

    感受一下Nimble

    // Swift
    expect(1 + 1).to(equal(2))
    expect(1.2).to(beCloseTo(1.1, within: 0.1))
    expect(3) > 2
    expect("seahorse").to(contain("sea"))
    expect(["Atlantic", "Pacific"]).toNot(contain("Mississippi"))
    expect(ocean.isClean).toEventually(beTruthy())
    

    是不是比XCTAssert()用起来舒服一些。

    得益于swift语法及闭包,相对于之前介绍的框架,Quick的可读性更好。例子如下:

    // Swift
    
    import Quick
    import Nimble
    
    class TableOfContentsSpec: QuickSpec {
      override func spec() {
        describe("the 'Documentation' directory") {
          it("has everything you need to get started") {
            let sections = Directory("Documentation").sections
            expect(sections).to(contain("Organized Tests with Quick Examples and Example Groups"))
            expect(sections).to(contain("Installing Quick"))
          }
    
          context("if it doesn't have what you're looking for") {
            it("needs to be updated") {
              let you = You(awesome: true)
              expect{you.submittedAnIssue}.toEventually(beTruthy())
            }
          }
        }
      }
    }
    

    用于UI测试的开源库

    相对于XCTest而言,由于苹果排斥第三方工具关于UI测试方面只有UIAutomation。剩下的方案只有hack了。

    KIF

    kif展开其实就是keep it functional,用OC写,基于XCTexst
    KIF的tester使用私有API访问视图层次,并通过视图的accessiblity label value进行交互。

    示例代码如下:

    - (void)testSuccessfulLogin {
      [tester enterText:@"user@example.com" intoViewWithAccessibilityLabel:@"Login User Name"];
      [tester enterText:@"thisismypassword" intoViewWithAccessibilityLabel:@"Login Password"];
      [tester tapViewWithAccessibilityLabel:@"Log In"];
    
      // Verify that the login succeeded
      [tester waitForTappableViewWithAccessibilityLabel:@"Welcome"];
    }
    

    注意:KIF需要被加入到项目中的Unit Test target而不是UI Test target

    总的来说是目前比较优秀的iOS开源库中UI 测试框架。
    这里有一篇美团分享的关于它的使用。详细介绍请看基于 KIF 的 iOS UI 自动化测试和持续集成

    Subliminal

    sublimnial是一个OC框架,和KIF对比而言,二者都是集成了XCTest,不同之处是sublimnial实在UIAtomation基础上实现的,而KIF是利用 苹果 给所有控件提供的辅助属性 accessibility attributes来定位和获取元素,完成界面的交互操作;结合使用 Xcode 的 XCTest 测试框架,拥有 XCTest 测试框架的特性,使得测试用例能以 command line build 工具运行并获取测试报告。

    示例代码:

    - (void)testLogInSucceedsWithUsernameAndPassword {
      SLTextField *usernameField = [SLTextField elementWithAccessibilityLabel:@"username field"];
      SLTextField *passwordField = [SLTextField elementWithAccessibilityLabel:@"password field" isSecure:YES];
      SLElement *submitButton = [SLElement elementWithAccessibilityLabel:@"Submit"];
      SLElement *loginSpinner = [SLElement elementWithAccessibilityLabel:@"Logging in..."];
    
      NSString *username = @"Jeff", *password = @"foo";
      [usernameField setText:username];
      [passwordField setText:password];
    
      [submitButton tap];
    
      // wait for the login spinner to disappear
      SLAssertTrueWithTimeout([loginSpinner isInvalidOrInvisible], 3.0, @"Log-in was not successful.");
    
      NSString *successMessage = [NSString stringWithFormat:@"Hello, %@!", username];
      SLAssertTrue([[SLElement elementWithAccessibilityLabel:successMessage] isValid],
      @"Log-in did not succeed.");
    
      // Check the internal state of the app.
      SLAssertTrue(SLAskAppYesNo(isUserLoggedIn), @"User is not logged in.")
    }
    

    不幸的是这个库已经很久很久没有维护了。

    Calabash

    上面介绍的框架都是针对于iOS或者OSX,Calabash是一个跨平台的测试框架。Xamarin维护这种鸽项目,可能有些同学对Xamarin不是很熟悉,这个公司主要使用C#来写iOS和Android应用程序。

    不像KIF和Subliminal不用和Xcode集成,但是写方法就和OC有比较大的区别。因为Calabash是基于Ruby的。

    示例代码:

    # rating_a_stand.feature
    
    Feature: Rating a stand
      Scenario: Find and rate a stand from the list
        Given I am on the foodstand list
        Then I should see a "rating" button
        And I should not see "Dixie Burger & Gumbo Soup"
    
    # steps.rb
    
    Given(/^I am on the foodstand list$/) do
      wait_for_element_exists "view marked:'Foodstand'"
    end
    
    Given(/^I should see a "([^\"]*)" button$/) do |button_title|
      wait_for_element_exists "button marked:'#{button_title}'"
    end
    
    Given(/^I should not see "([^\"]*)"$/) do |view_label|
      wait_for_element_does_not_exists "view marked:'#{view_label}'
    end
    

    目前本人还没有用过这个牛逼的测试框架。如果有人感兴趣可以尝试一下。Calabash官网

    聊聊其他

    上面粗略的介绍了iOS或者OSX官方自带及开源的测试框架。只是起到了入门简单介绍的作用。读者完全可以自己实践体验下一下各个框架的优劣。

    聊了下测试相关的,如果再继续深入。就是持续集成,持续部署这些了。这块网上也有不少文章介绍的。

    Have Fun!

    相关文章

      网友评论

        本文标题:聊聊iOS&OSX测试相关的八卦

        本文链接:https://www.haomeiwen.com/subject/bodrpttx.html