[iOS] XCTestCase實作

SC Tuan
SC Tuan
Jul 26, 2017 · 4 min read

最近要寫Test case,所以這邊會紀錄我一連串的測試與學習。

加入一個Test Target

如果你的專案一開始沒有Test Target,那你要加入一個Test Target,到add target,選擇 iOS Unit Testing Bundle,然後命名。

XCTestCase結構

以下是Test Case的class會有的方法。

- (void)setUp {
[super setUp];
// Put setup code here. This method is called before the invocation of each test method in the class.
}
- (void)tearDown {
// Put teardown code here. This method is called after the
//invocation of each test method in the class.
[super tearDown];
}

setUp就是在每次測試方法開始前會呼叫,做一些前置作業,你可以在這邊先設定好固定需要執行的東西。

tearDown就是執行完任一次test之後會呼叫的,目的是清除善後,以維護下一次要開始的測試是乾淨的。

XCTest方法

  • XCTAssertNil(expression, …):如果expresssion裡面是nil,那就成功,反之就失敗,會印出後面帶有的訊息。
  • XCTAssertNotNil(expression, …):和上面相反,expression裡面不是nil才算是成功。
  • XCTAssert(expression, …):expression為真時就是成功。
  • XCTAssertTrue(expression, …):和XCTAssert一樣。
  • XCTAssertFalse(expression, …):和XCTAssert相反。
  • XCTAssertEqualObjects(expression1, expression2, …):expression1和 expression2相同時,測試即通過。如果兩個expression都是字串,那他會比較字串是否相同,所以會以該物件的equal標準為主。
  • XCTAssertNotEqualObjects(expression1, expression2, …):跟XCTAssertEqualObjects相反。
  • XCTAssertEqual(expression1, expression2, …):作為參數的expression要為C scalar type,但實際測試中,NSString也可以用。主要邏輯同XCTAssertEqualObjects。
  • XCTAssertNotEqual(expression1, expression2, …):說明同XCTAssertEqual,邏輯和XCTAssertEqual相反。
  • XCTAssertEqualWithAccuracy(expression1, expression2, accuracy, …):比較expression1和expression2兩者數值上的差異度來決定兩者是不是一樣,比方說10.001和10.0001,accuracy為0.001時,可以看成相同的(兩者相減的絕對值為0.0009,小於0.001)。
  • XCTAssertNotEqualWithAccuracy(expression1, expression2, accuracy, …):同上,邏輯相反。

先列這些,不然太長了,其他的可以自己試試看。

Trouble Shooting

Cocoapod import問題

實際的code會用到pod時,test class如果無法搜尋到相關的pod,這通常是因為你沒有做一份pod給test。

你可以打開project > Info > Configurations > Debug,點開後會看到Debug下有個列表,YourProjectName和YourProjectNameTests (YourProjectName是你的專案名稱),你看右邊對應的是不是Pod-YourProjectNameTest.debug,還是none?如果是none,表示你沒有做一份Pod給Test bundle用。

打開Podfile,在最下面加入

target 'YourProjectNameTests' doend

然後 pod install就可以了。

Swift.h import問題

Test可能會遇到無法使用Swift header的問題,我查到的做法是,到Test的Target,選Build Settings的Search Paths裡面的Header Search Paths,加入

"$(TARGET_TEMP_DIR)/../$(PROJECT_NAME).build/DerivedSources"

然後就可以了。

SC Tuan

Written by

SC Tuan

iOS developer😘 / Web developer🤪/ anymore? 😎

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade