使用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; // 測試提前返回
    }
    // 復雜操作...
}

參考資料

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 發現 關注 消息 iOS 第三方庫、插件、知名博客總結 作者大灰狼的小綿羊哥哥關注 2017.06.26 09:4...
    肇東周閱讀 12,180評論 4 61
  • 出國部
    dddfrog閱讀 273評論 0 0
  • 智能商業雙螺旋:制造大公司 隨著騰訊和阿里巴巴先后突破3000億美金的市值,全世界前十大企業里面已經有五家是純互聯...
    妘如雪閱讀 504評論 0 1
  • 今天回了老家一趟,回了家之后,和鄰居聊聊,今年因為天旱,老百姓的日子不好過,東西都不值錢。談了比較多,老百姓...
    呂諾爸閱讀 139評論 0 3
  • 外甥女問我生活的家 我歪著腦袋,一心一意地說 屋頂很高,光線讓人心里癢癢 從你家往這看仿佛是遠山。 我住在陽光房里...
    倩何人換取閱讀 317評論 0 1