SlideShare a Scribd company logo
iOS Unit test
getting started
Liyao Chen @ KKBOX
Outlines
• What is unit testing?
• Unit testing
• Why is unit testing important?
What is unit testing?
–Roy Osherove
通過調⽤用公共⽅方法產⽣生⼀一個測試的可⾒見結果
What is unit testing?
(⾦金迎 譯)
–wiki
Unit testing is a software testing method to
determine whether they are fit for use.
單元測試是定義程式碼符合需求的⽅方法
What is unit testing?
–Stephen Ritchie
“performing intention checking”
The unit tests check that the program works
and continues to work as the developer
intended or planned for it to work.
單元測試檢驗程式碼是否按照開發者的計畫執⾏行
What is unit testing?
Work as the developer intended?
Work as intended
你跟著師⽗父去幫別⼈人佈線安裝電燈,師⽗父三兩下
就搞定了,然後請你確認有沒有裝好,請問你會
怎麼做?
打開開關看看電燈有沒有跟著亮

再關上開關看電燈有沒有跟著暗
Work as intended
Work as intended
1. 執⾏行模擬器

2. 移動到你要測試的程式碼區塊
3. 確認程式碼如預期執⾏行
最費時
如果你要測試的程式碼在第10⾴頁呢?
Work as intended
1. 執⾏行模擬器

2. 移動到你要測試的程式碼區塊
3. 確認程式碼如預期執⾏行
如果可以跳過第⼆二步呢?
<0.2 seconds
Work as intended
Unit testing
• Unit test 3A rules
• 驗證的⼿手法
• XCTest
• 優秀的單元測試
Unit test 3A Rules
• Arrange: Get the environment ready.
• Act: Call the method under test.
• Assert: Ensure that what you expected to
happen, happened.
前置設定 > 動作 > 衡量結果
Unit test 3A Rules
前置設定 > 動作 > 衡量結果
關燈的房間 > 按下電燈開關 > 電燈打開(開燈的房間)
Spec: 測試房間電燈開關是否正常運作。
關燈的房間 > 按下電燈開關 > 電燈打開(開燈的房間)
驗證的⼿手法
如何程式化?
驗證的⼿手法
• 回傳值
• 狀態
• 互動
驗證的⼿手法 - 驗證回傳值
#import "LCCalculator.h"
@interface LCCalculatorTests : XCTestCase
@end
@implementation LCCalculatorTests
// 驗證回傳值
- (void)testSum
{
//Arrange
LCCalculator *calculator = [[LCCalculator alloc] init];
NSNumber *a = @10;
NSNumber *b = @5;
//Act
NSNumber *result = [calculator sumWithA:a andB:b];
//Assert
XCTAssertTrue([result isEqualToNumber:@15]);
}
@end
#import "LCRoom.h"
@interface LCRoomTests : XCTestCase
@end
@implementation LCRoomTests
#pragma mark - openLight
// 驗證狀態
// 關燈的房間 > 按下電燈開關 > 電燈打開 (開燈的房間)
- (void)testOpenLightWhenLightOff
{
//Arrange - 關燈的房間
LCRoom *room = [[LCRoom alloc] initWithLight:NO];
//Act - 按下電燈開關
[room openLight];
//Assert - 電燈打開 (開燈的房間)
XCTAssertTrue(room.isLight);
}
@end
驗證的⼿手法 - 驗證狀態
#import "LCRoom.h"
#import "LCHouse.h"
@interface LCHouseTests : XCTestCase
@end
@implementation LCHouseTests
//驗證互動
- (void)testTurnOffHouseLight
{
//Arrange
LCRoom *roomA = [[LCRoom alloc] initWithLight:YES];
LCRoom *roomB = [[LCRoom alloc] initWithLight:YES];
LCHouse *house = [[LCHouse alloc] initWithRooms:@[roomA, roomB]];
//Act
[house turnOffHouseLight];
//Assert
XCTAssertFalse(roomA.isLight);
XCTAssertFalse(roomB.isLight);
}
@end
驗證的⼿手法 - 驗證互動
#import "DummyUITableViewDataSource.h"
@interface LCTableViewTests : XCTestCase
@end
@implementation LCTableViewTests
//驗證互動
- (void)testExample
{
//Arrange
DummyUITableViewDataSource *dataSource = [[DummyUITableViewDataSource alloc] init];
UITableView *tableView = [[UITableView alloc] init];
tableView.dataSource = dataSource;
//Act
[tableView reloadData];
//Assert
NSInteger rowCount = [tableView numberOfRowsInSection:0];
XCTAssertEqual(rowCount, 40);
}
@end
驗證的⼿手法 - 驗證互動
XCTest
#import <UIKit/UIKit.h>
#import <XCTest/XCTest.h>
@interface ValueTests : XCTestCase
@end
@implementation ValueTests
- (void)testExample {
XCTAssertNil(nil);
XCTAssertNotNil(@"123");
XCTAssertTrue(YES, @"Pass");
XCTAssertFalse(NO, @"Pass");
XCTAssertEqual(10, 10, @"Pass");
XCTAssertTrue([@"123" isEqualToString:@"123"]);
XCTAssertGreaterThan(10, 5);
XCTAssertLessThan(5, 7);
}
@end
Tests 後綴
test 前綴
Assertion
Why is unit testing important?
Why is unit testing important? - objc.io issue 15-4
• 避免代碼惡化

惡化在什麼時候發⽣生?在你修改代碼的時候
• 使重構更簡單

你可以⾃自信的修改實現細節,不害怕改壞其他程式碼
• 減少了創造軟體的時間

通過更快速地修改代碼,出錯時測試會告訴你哪裡錯
• 提供了可執⾏行的說明和⽂文檔 

你在什麼時候更想知道軟體實際上是如何運作的?在你想
修改它們的時候
Why is unit testing important? - objc.io issue 15-2
目前為止,我們的編碼庫已經縱橫 190 個文件和
18,000 行代碼,達到了 544 kB。我們測試部分的代碼
現在差不多有1,200 kB,大概是被測試代碼的兩倍。
– Arne Schroppe and Daniel Eggert
Why is unit testing important?
–Zonble
SQLite 的測試⼤大約是原始碼的⼀一千倍
How you choose
open source?
Why is unit testing important?
Why is unit testing important?
Star?
Why is unit testing important?
Document?
Why is unit testing important?
Tests result?
Why is unit testing important?
- (void)testBasicOnSuccess 

{
[[[BFTask taskWithResult:@"foo"] continueWithSuccessBlock:^id(BFTask
*task)
{
XCTAssertEqualObjects(@"foo", task.result);
return nil;
}] waitUntilFinished];
}
task.result == 傳⼊入物件
Why is unit testing important?
- (void)testBasicOnSuccessWithToken 

{
BFCancellationTokenSource *cts = [BFCancellationTokenSource
cancellationTokenSource];
BFTask *task = [BFTask taskWithDelay:100];
task = [task continueWithExecutor:[BFExecutor immediateExecutor]
successBlock:^id(BFTask *task) {
XCTFail(@"Success block should not be
triggered");
return nil;
}
cancellationToken:cts.token];
[cts cancel];
[task waitUntilFinished];
XCTAssertTrue(task.isCancelled);
}
可以取消⽽而且 isCancelled 會標記
Trust
Why is unit testing important?
優秀的單元測試
• 時機(Timely)
• 容易理解(Easy)
• 快速(Fast)
• 隔離(Isolated)
• 可重複(Repeatable)
• ⾃自我檢驗(Self-verifying)
優秀的單元測試 I
• 容易理解(Easy)

團隊中任何⼀一⼈人都能看懂、它應該第⼆二天還有意義、如果它失敗了,應該很
容易發現原因是什麼,去追朔到問題所在
• 可重複(Repeatable) 

每次運⾏行測試都應該產⽣生相同的結果
• 快速(Fast)

測試應該能夠被經常執⾏行、在幾分鐘內完成所有單元測試
優秀的單元測試 II with TDD
• 隔離(Isolated)

測試本⾝身不依賴外部因素或者其他測試的結果(獨⽴立於其他測試的運⾏行)
• 帶⾃自檢(Self-verifying)

測試應該包括斷⾔言,不需要⼈人為干預
• 時機(Timely)

測試應該和產品代碼⼀一同書寫
Unit testing for me is …
Testing is spec
Testing is memory
If you can’t remember how you die(crash) last time.
How to evolute your software?
Summary
• 確保程式碼持續按照計畫執⾏行的⽅方法
• 對程式碼與修改程式碼產⽣生信⼼心
• 幫你記住曾經犯下的錯誤,並且預防再犯
QnA
• 測試不是QA的⼯工作嗎?
• 寫測試會花我很多時間
• 寫測試是為了Debug嗎?
• 沒有測試我也可以寫出⼀一樣的程式碼,那為什麼需要
測試?
• SDK升級的⼩小故事
• 哪些地⽅方⼀一定要測?
We are hiring!
@ KKBOX
待續
• 測試為什麼重要
• 如何寫出好的單元測試
• 測試驅動開發(TDD)
• ⾏行為驅動開發(BDD)
Reference
• http://kevjenkins.blogspot.tw
• http://www.ithome.com.tw/news/90500
• http://www.objc.io/issues/15-testing/
• http://blog.miniasp.com/post/2010/02/21/The-
Art-of-Unit-Testing-with-Roy-Osherove-
Notes.aspx
Other links
• Sample code

https://github.com/gliyao/LCUnitTestsExample
• Note

https://www.evernote.com/l/
AA-0a-6p00NHiLVAY_OTIDJ64J6jMPiU2zM

More Related Content

What's hot (20)

PPTX
Grails Spock Testing
TO THE NEW | Technology
 
PDF
Testing for software engineers
Mohammed Ashour
 
KEY
iOS Unit Testing
sgleadow
 
PPTX
Unit testing
NexThoughts Technologies
 
PDF
Writing good unit test
Lucy Lu
 
PDF
Javascript tdd byandreapaciolla
Andrea Paciolla
 
PDF
C++ Unit Test with Google Testing Framework
Humberto Marchezi
 
PDF
Workshop unit test
Francesco Garavaglia
 
PPTX
Junit4&testng presentation
Sanjib Dhar
 
PDF
Agile Swift
Godfrey Nolan
 
PPT
Unit testing with java
Dinuka Malalanayake
 
PPT
Unit testing with Spock Framework
Eugene Dvorkin
 
PDF
Unit testing in android
Li-Wei Cheng
 
PPTX
Selenium with java
Gousalya Ramachandran
 
PPT
Unit Testing in iOS - Ninjava Talk
Long Weekend LLC
 
PDF
What's software testing
Li-Wei Cheng
 
KEY
Unit testing for 40 square software
Ruben Tan
 
PDF
Python unittest
Felipe Ruhland
 
Grails Spock Testing
TO THE NEW | Technology
 
Testing for software engineers
Mohammed Ashour
 
iOS Unit Testing
sgleadow
 
Writing good unit test
Lucy Lu
 
Javascript tdd byandreapaciolla
Andrea Paciolla
 
C++ Unit Test with Google Testing Framework
Humberto Marchezi
 
Workshop unit test
Francesco Garavaglia
 
Junit4&testng presentation
Sanjib Dhar
 
Agile Swift
Godfrey Nolan
 
Unit testing with java
Dinuka Malalanayake
 
Unit testing with Spock Framework
Eugene Dvorkin
 
Unit testing in android
Li-Wei Cheng
 
Selenium with java
Gousalya Ramachandran
 
Unit Testing in iOS - Ninjava Talk
Long Weekend LLC
 
What's software testing
Li-Wei Cheng
 
Unit testing for 40 square software
Ruben Tan
 
Python unittest
Felipe Ruhland
 

Viewers also liked (20)

DOCX
Scope & sequence 2010
vpreddey
 
PPSX
Centrifuge slide show
jenniferporter
 
PPTX
Going Global
Andrus Viirg
 
PDF
Zend cache evolution.владимир дубина
Andrey Tokarchuk
 
PDF
ITMI Symposium 2013 brochure
TedBravos
 
PDF
Dinámica económica, desarrollo productivo exportador de lambayeque
AREX Lambayeque
 
PPTX
Evaluation presentation
heatheraveyard
 
PPT
Changes Afoot: Changing Relationships between Engaged Patients and Docs in Ca...
H. Jack West
 
PPTX
Productos Hall Mg Consulting
Klau Noche
 
KEY
Nine Immediate Steps to a Better Website
Paul Boomer
 
PPT
Fisk escabeche
heleverdeniskole
 
PPTX
On Target
Provenperformance
 
PDF
Mekong Club - an introduction
themekongclub
 
PPTX
After Dark (demented
nsasu94
 
PPTX
Production log
nsasu94
 
KEY
Human trafficking myths and the terms we use
themekongclub
 
PDF
Mwafy bf feb 12 web
Hany Mwafy
 
PDF
Ti25 brochure
FlukeinMalta
 
PPT
Fcds mid term-Rules of the Road Test 10/26/11
dalufcds
 
PDF
Evgeniy chilevskiy
Andrey Tokarchuk
 
Scope & sequence 2010
vpreddey
 
Centrifuge slide show
jenniferporter
 
Going Global
Andrus Viirg
 
Zend cache evolution.владимир дубина
Andrey Tokarchuk
 
ITMI Symposium 2013 brochure
TedBravos
 
Dinámica económica, desarrollo productivo exportador de lambayeque
AREX Lambayeque
 
Evaluation presentation
heatheraveyard
 
Changes Afoot: Changing Relationships between Engaged Patients and Docs in Ca...
H. Jack West
 
Productos Hall Mg Consulting
Klau Noche
 
Nine Immediate Steps to a Better Website
Paul Boomer
 
Fisk escabeche
heleverdeniskole
 
Mekong Club - an introduction
themekongclub
 
After Dark (demented
nsasu94
 
Production log
nsasu94
 
Human trafficking myths and the terms we use
themekongclub
 
Mwafy bf feb 12 web
Hany Mwafy
 
Ti25 brochure
FlukeinMalta
 
Fcds mid term-Rules of the Road Test 10/26/11
dalufcds
 
Evgeniy chilevskiy
Andrey Tokarchuk
 
Ad

Similar to iOS Unit test getting stared (10)

PDF
iOS Testing
Derrick Chao
 
PDF
淺談高效撰寫單元測試
Zen K.C
 
PDF
iOS UI Testing in Xcode
Jz Chang
 
PDF
A Comprehensive Guide to Efficiently Writing and Implementing iOS Unit Tests.pdf
flufftailshop
 
PDF
Introduction to Unit Testing
Swanky Hsiao
 
PDF
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Robot Media
 
PDF
iOS Unit testing II
Liyao Chen
 
PPS
Unit testing_pps
Gaurav Keshre
 
PPTX
单元测试必知必会
智杰 付
 
PDF
Unit testing, principles
Renato Primavera
 
iOS Testing
Derrick Chao
 
淺談高效撰寫單元測試
Zen K.C
 
iOS UI Testing in Xcode
Jz Chang
 
A Comprehensive Guide to Efficiently Writing and Implementing iOS Unit Tests.pdf
flufftailshop
 
Introduction to Unit Testing
Swanky Hsiao
 
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Robot Media
 
iOS Unit testing II
Liyao Chen
 
Unit testing_pps
Gaurav Keshre
 
单元测试必知必会
智杰 付
 
Unit testing, principles
Renato Primavera
 
Ad

More from Liyao Chen (20)

PDF
KKBOX WWDC17 Xcode IDE - Hardy
Liyao Chen
 
PDF
KKBOX WWDC17 Xcode debug - Oliver
Liyao Chen
 
PDF
KKBOX WWDC17 WatchOS - Dada
Liyao Chen
 
PDF
KKBOX WWDC17 UIKit Drag and Drop - Mario
Liyao Chen
 
PDF
KKBOX WWDC17 UIKit - QQ
Liyao Chen
 
PDF
KKBOX WWDC17 Swift and Foundation - Liyao
Liyao Chen
 
PDF
KKBOX WWDC17 SiriKit and CoreSpotlight - Seraph
Liyao Chen
 
PDF
KKBOX WWDC17 Security - Antony
Liyao Chen
 
PDF
KKBOX WWDC17 Performance and Testing - Hokila
Liyao Chen
 
PDF
KKBOX WWDC17 Notification and Autolayout - Jefferey
Liyao Chen
 
PDF
KKBOX WWDC17 Airplay 2 - Dolphin
Liyao Chen
 
PDF
KKBOX WWDC17 Core Image - Daniel Tien
Liyao Chen
 
PDF
Auto Layout part 1
Liyao Chen
 
PDF
Continuous Integration
Liyao Chen
 
PDF
iOS Design to Code - Code
Liyao Chen
 
PDF
iOS Design to Code - Design
Liyao Chen
 
PDF
Beta testing with CI
Liyao Chen
 
PPTX
PTTHOT x IDEAS_HACKATHON 2014
Liyao Chen
 
PDF
選擇
Liyao Chen
 
PDF
Windows 8 apps dev.整理及分享
Liyao Chen
 
KKBOX WWDC17 Xcode IDE - Hardy
Liyao Chen
 
KKBOX WWDC17 Xcode debug - Oliver
Liyao Chen
 
KKBOX WWDC17 WatchOS - Dada
Liyao Chen
 
KKBOX WWDC17 UIKit Drag and Drop - Mario
Liyao Chen
 
KKBOX WWDC17 UIKit - QQ
Liyao Chen
 
KKBOX WWDC17 Swift and Foundation - Liyao
Liyao Chen
 
KKBOX WWDC17 SiriKit and CoreSpotlight - Seraph
Liyao Chen
 
KKBOX WWDC17 Security - Antony
Liyao Chen
 
KKBOX WWDC17 Performance and Testing - Hokila
Liyao Chen
 
KKBOX WWDC17 Notification and Autolayout - Jefferey
Liyao Chen
 
KKBOX WWDC17 Airplay 2 - Dolphin
Liyao Chen
 
KKBOX WWDC17 Core Image - Daniel Tien
Liyao Chen
 
Auto Layout part 1
Liyao Chen
 
Continuous Integration
Liyao Chen
 
iOS Design to Code - Code
Liyao Chen
 
iOS Design to Code - Design
Liyao Chen
 
Beta testing with CI
Liyao Chen
 
PTTHOT x IDEAS_HACKATHON 2014
Liyao Chen
 
選擇
Liyao Chen
 
Windows 8 apps dev.整理及分享
Liyao Chen
 

Recently uploaded (20)

PDF
advancepresentationskillshdhdhhdhdhdhhfhf
jasmenrojas249
 
PPTX
Web Testing.pptx528278vshbuqffqhhqiwnwuq
studylike474
 
PDF
Infrastructure planning and resilience - Keith Hastings.pptx.pdf
Safe Software
 
PDF
Salesforce Pricing Update 2025: Impact, Strategy & Smart Cost Optimization wi...
GetOnCRM Solutions
 
PDF
New Download FL Studio Crack Full Version [Latest 2025]
imang66g
 
PPT
Activate_Methodology_Summary presentatio
annapureddyn
 
PDF
10 posting ideas for community engagement with AI prompts
Pankaj Taneja
 
PDF
How to Download and Install ADT (ABAP Development Tools) for Eclipse IDE | SA...
SAP Vista, an A L T Z E N Company
 
PPTX
TRAVEL APIs | WHITE LABEL TRAVEL API | TOP TRAVEL APIs
philipnathen82
 
PDF
AI Image Enhancer: Revolutionizing Visual Quality”
docmasoom
 
PPTX
GALILEO CRS SYSTEM | GALILEO TRAVEL SOFTWARE
philipnathen82
 
PPTX
Farrell__10e_ch04_PowerPoint.pptx Programming Logic and Design slides
bashnahara11
 
PDF
WatchTraderHub - Watch Dealer software with inventory management and multi-ch...
WatchDealer Pavel
 
PPTX
Contractor Management Platform and Software Solution for Compliance
SHEQ Network Limited
 
PDF
Using licensed Data Loss Prevention (DLP) as a strategic proactive data secur...
Q-Advise
 
PDF
System Center 2025 vs. 2022; What’s new, what’s next_PDF.pdf
Q-Advise
 
PDF
Applitools Platform Pulse: What's New and What's Coming - July 2025
Applitools
 
PDF
MiniTool Power Data Recovery Crack New Pre Activated Version Latest 2025
imang66g
 
PDF
Enhancing Security in VAST: Towards Static Vulnerability Scanning
ESUG
 
PDF
Enhancing Healthcare RPM Platforms with Contextual AI Integration
Cadabra Studio
 
advancepresentationskillshdhdhhdhdhdhhfhf
jasmenrojas249
 
Web Testing.pptx528278vshbuqffqhhqiwnwuq
studylike474
 
Infrastructure planning and resilience - Keith Hastings.pptx.pdf
Safe Software
 
Salesforce Pricing Update 2025: Impact, Strategy & Smart Cost Optimization wi...
GetOnCRM Solutions
 
New Download FL Studio Crack Full Version [Latest 2025]
imang66g
 
Activate_Methodology_Summary presentatio
annapureddyn
 
10 posting ideas for community engagement with AI prompts
Pankaj Taneja
 
How to Download and Install ADT (ABAP Development Tools) for Eclipse IDE | SA...
SAP Vista, an A L T Z E N Company
 
TRAVEL APIs | WHITE LABEL TRAVEL API | TOP TRAVEL APIs
philipnathen82
 
AI Image Enhancer: Revolutionizing Visual Quality”
docmasoom
 
GALILEO CRS SYSTEM | GALILEO TRAVEL SOFTWARE
philipnathen82
 
Farrell__10e_ch04_PowerPoint.pptx Programming Logic and Design slides
bashnahara11
 
WatchTraderHub - Watch Dealer software with inventory management and multi-ch...
WatchDealer Pavel
 
Contractor Management Platform and Software Solution for Compliance
SHEQ Network Limited
 
Using licensed Data Loss Prevention (DLP) as a strategic proactive data secur...
Q-Advise
 
System Center 2025 vs. 2022; What’s new, what’s next_PDF.pdf
Q-Advise
 
Applitools Platform Pulse: What's New and What's Coming - July 2025
Applitools
 
MiniTool Power Data Recovery Crack New Pre Activated Version Latest 2025
imang66g
 
Enhancing Security in VAST: Towards Static Vulnerability Scanning
ESUG
 
Enhancing Healthcare RPM Platforms with Contextual AI Integration
Cadabra Studio
 

iOS Unit test getting stared