Submit Search
Upload
iOS Unit Testing - Break Dependencies with Protocols, Dummies, and Mocks
•
13 likes
•
1,988 views
AI-enhanced title
Liyao Chen
Follow
外部依賴所造成的問題,用Protocol與mock的方式去破除依賴。
Read less
Read more
Software
Slideshow view
Report
Share
Slideshow view
Report
Share
1 of 28
Download now
Download to read offline
Recommended
Ccrs 10122015
Ccrs 10122015
Dirdop
Acta 2011 mar 08
Acta 2011 mar 08
Cristian Cabezas Diaz
Partner Update 18 October 2012
Partner Update 18 October 2012
newcastlegateshead
West Immunotherapy, Vaccines for Lung Cancer Mage-A3, Stimuvax, and Lucanix
West Immunotherapy, Vaccines for Lung Cancer Mage-A3, Stimuvax, and Lucanix
H. Jack West
NewcastleGateshead Initiative Partner Update Meeting 11.06.2015
NewcastleGateshead Initiative Partner Update Meeting 11.06.2015
newcastlegateshead
Fluke Test Tools Catalog 2010/2011
Fluke Test Tools Catalog 2010/2011
FlukeinMalta
Windows 8 apps dev.整理及分享
Windows 8 apps dev.整理及分享
Liyao Chen
Lectores y escritores
Lectores y escritores
Lusy Chisag
Recommended
Ccrs 10122015
Ccrs 10122015
Dirdop
Acta 2011 mar 08
Acta 2011 mar 08
Cristian Cabezas Diaz
Partner Update 18 October 2012
Partner Update 18 October 2012
newcastlegateshead
West Immunotherapy, Vaccines for Lung Cancer Mage-A3, Stimuvax, and Lucanix
West Immunotherapy, Vaccines for Lung Cancer Mage-A3, Stimuvax, and Lucanix
H. Jack West
NewcastleGateshead Initiative Partner Update Meeting 11.06.2015
NewcastleGateshead Initiative Partner Update Meeting 11.06.2015
newcastlegateshead
Fluke Test Tools Catalog 2010/2011
Fluke Test Tools Catalog 2010/2011
FlukeinMalta
Windows 8 apps dev.整理及分享
Windows 8 apps dev.整理及分享
Liyao Chen
Lectores y escritores
Lectores y escritores
Lusy Chisag
саранчимэг цахим судалгаа 1
саранчимэг цахим судалгаа 1
saraa79
Learning Technologies Presentation 2011
Learning Technologies Presentation 2011
brownh2
ClassDojo guía para estudiantes
ClassDojo guía para estudiantes
Nahum Mota Martinez
Calterna
Calterna
Leandro __
Mod de viata sanatos 2
Mod de viata sanatos 2
Pishta Bmc
Health System Transformation
Health System Transformation
The Scarborough Hospital
Trabajo nuevo 3
Trabajo nuevo 3
alejoxs
Business leaders' briefing 24.09.2014
Business leaders' briefing 24.09.2014
newcastlegateshead
Costume & Props
Costume & Props
nsasu94
Ti32 Data Sheet
Ti32 Data Sheet
FlukeinMalta
ProtectIV
ProtectIV
Henrique Outeda
irem waseem, economic system
irem waseem, economic system
Irem Waseem
After Dark (demented
After Dark (demented
nsasu94
Tarragona romana
Tarragona romana
davidmanx
plegable molecular
plegable molecular
Heyly
Partner update meeting 13.06.14 final
Partner update meeting 13.06.14 final
newcastlegateshead
Ellis island
Ellis island
leslyn0329
Daniela pict
Daniela pict
nsasu94
Concurrency in Eclipse: Best Practices and Gotchas
Concurrency in Eclipse: Best Practices and Gotchas
amccullo
Resilience and chaos engineering
Resilience and chaos engineering
Eric Wyles
Mock Objects, Design and Dependency Inversion Principle
Mock Objects, Design and Dependency Inversion Principle
P Heinonen
SiliconFailsafeForIoT_Doin
SiliconFailsafeForIoT_Doin
Jonny Doin
More Related Content
Viewers also liked
саранчимэг цахим судалгаа 1
саранчимэг цахим судалгаа 1
saraa79
Learning Technologies Presentation 2011
Learning Technologies Presentation 2011
brownh2
ClassDojo guía para estudiantes
ClassDojo guía para estudiantes
Nahum Mota Martinez
Calterna
Calterna
Leandro __
Mod de viata sanatos 2
Mod de viata sanatos 2
Pishta Bmc
Health System Transformation
Health System Transformation
The Scarborough Hospital
Trabajo nuevo 3
Trabajo nuevo 3
alejoxs
Business leaders' briefing 24.09.2014
Business leaders' briefing 24.09.2014
newcastlegateshead
Costume & Props
Costume & Props
nsasu94
Ti32 Data Sheet
Ti32 Data Sheet
FlukeinMalta
ProtectIV
ProtectIV
Henrique Outeda
irem waseem, economic system
irem waseem, economic system
Irem Waseem
After Dark (demented
After Dark (demented
nsasu94
Tarragona romana
Tarragona romana
davidmanx
plegable molecular
plegable molecular
Heyly
Partner update meeting 13.06.14 final
Partner update meeting 13.06.14 final
newcastlegateshead
Ellis island
Ellis island
leslyn0329
Daniela pict
Daniela pict
nsasu94
Viewers also liked
(18)
саранчимэг цахим судалгаа 1
саранчимэг цахим судалгаа 1
Learning Technologies Presentation 2011
Learning Technologies Presentation 2011
ClassDojo guía para estudiantes
ClassDojo guía para estudiantes
Calterna
Calterna
Mod de viata sanatos 2
Mod de viata sanatos 2
Health System Transformation
Health System Transformation
Trabajo nuevo 3
Trabajo nuevo 3
Business leaders' briefing 24.09.2014
Business leaders' briefing 24.09.2014
Costume & Props
Costume & Props
Ti32 Data Sheet
Ti32 Data Sheet
ProtectIV
ProtectIV
irem waseem, economic system
irem waseem, economic system
After Dark (demented
After Dark (demented
Tarragona romana
Tarragona romana
plegable molecular
plegable molecular
Partner update meeting 13.06.14 final
Partner update meeting 13.06.14 final
Ellis island
Ellis island
Daniela pict
Daniela pict
Similar to iOS Unit Testing - Break Dependencies with Protocols, Dummies, and Mocks
Concurrency in Eclipse: Best Practices and Gotchas
Concurrency in Eclipse: Best Practices and Gotchas
amccullo
Resilience and chaos engineering
Resilience and chaos engineering
Eric Wyles
Mock Objects, Design and Dependency Inversion Principle
Mock Objects, Design and Dependency Inversion Principle
P Heinonen
SiliconFailsafeForIoT_Doin
SiliconFailsafeForIoT_Doin
Jonny Doin
Sneak Peek into the Future with Prof. Indranil Sengupta, IIT Kharagpur
Sneak Peek into the Future with Prof. Indranil Sengupta, IIT Kharagpur
Priyanka Aash
New and improved hacking oracle from web apps sumit sidharth
New and improved hacking oracle from web apps sumit sidharth
owaspindia
Similar to iOS Unit Testing - Break Dependencies with Protocols, Dummies, and Mocks
(6)
Concurrency in Eclipse: Best Practices and Gotchas
Concurrency in Eclipse: Best Practices and Gotchas
Resilience and chaos engineering
Resilience and chaos engineering
Mock Objects, Design and Dependency Inversion Principle
Mock Objects, Design and Dependency Inversion Principle
SiliconFailsafeForIoT_Doin
SiliconFailsafeForIoT_Doin
Sneak Peek into the Future with Prof. Indranil Sengupta, IIT Kharagpur
Sneak Peek into the Future with Prof. Indranil Sengupta, IIT Kharagpur
New and improved hacking oracle from web apps sumit sidharth
New and improved hacking oracle from web apps sumit sidharth
More from Liyao Chen
KKBOX WWDC17 Xcode IDE - Hardy
KKBOX WWDC17 Xcode IDE - Hardy
Liyao Chen
KKBOX WWDC17 Xcode debug - Oliver
KKBOX WWDC17 Xcode debug - Oliver
Liyao Chen
KKBOX WWDC17 WatchOS - Dada
KKBOX WWDC17 WatchOS - Dada
Liyao Chen
KKBOX WWDC17 UIKit Drag and Drop - Mario
KKBOX WWDC17 UIKit Drag and Drop - Mario
Liyao Chen
KKBOX WWDC17 UIKit - QQ
KKBOX WWDC17 UIKit - QQ
Liyao Chen
KKBOX WWDC17 Swift and Foundation - Liyao
KKBOX WWDC17 Swift and Foundation - Liyao
Liyao Chen
KKBOX WWDC17 SiriKit and CoreSpotlight - Seraph
KKBOX WWDC17 SiriKit and CoreSpotlight - Seraph
Liyao Chen
KKBOX WWDC17 Security - Antony
KKBOX WWDC17 Security - Antony
Liyao Chen
KKBOX WWDC17 Performance and Testing - Hokila
KKBOX WWDC17 Performance and Testing - Hokila
Liyao Chen
KKBOX WWDC17 Notification and Autolayout - Jefferey
KKBOX WWDC17 Notification and Autolayout - Jefferey
Liyao Chen
KKBOX WWDC17 Airplay 2 - Dolphin
KKBOX WWDC17 Airplay 2 - Dolphin
Liyao Chen
KKBOX WWDC17 Core Image - Daniel Tien
KKBOX WWDC17 Core Image - Daniel Tien
Liyao Chen
Auto Layout part 1
Auto Layout part 1
Liyao Chen
iOS Unit test getting stared
iOS Unit test getting stared
Liyao Chen
Continuous Integration
Continuous Integration
Liyao Chen
iOS Design to Code - Code
iOS Design to Code - Code
Liyao Chen
iOS Design to Code - Design
iOS Design to Code - Design
Liyao Chen
Beta testing with CI
Beta testing with CI
Liyao Chen
PTTHOT x IDEAS_HACKATHON 2014
PTTHOT x IDEAS_HACKATHON 2014
Liyao Chen
選擇
選擇
Liyao Chen
More from Liyao Chen
(20)
KKBOX WWDC17 Xcode IDE - Hardy
KKBOX WWDC17 Xcode IDE - Hardy
KKBOX WWDC17 Xcode debug - Oliver
KKBOX WWDC17 Xcode debug - Oliver
KKBOX WWDC17 WatchOS - Dada
KKBOX WWDC17 WatchOS - Dada
KKBOX WWDC17 UIKit Drag and Drop - Mario
KKBOX WWDC17 UIKit Drag and Drop - Mario
KKBOX WWDC17 UIKit - QQ
KKBOX WWDC17 UIKit - QQ
KKBOX WWDC17 Swift and Foundation - Liyao
KKBOX WWDC17 Swift and Foundation - Liyao
KKBOX WWDC17 SiriKit and CoreSpotlight - Seraph
KKBOX WWDC17 SiriKit and CoreSpotlight - Seraph
KKBOX WWDC17 Security - Antony
KKBOX WWDC17 Security - Antony
KKBOX WWDC17 Performance and Testing - Hokila
KKBOX WWDC17 Performance and Testing - Hokila
KKBOX WWDC17 Notification and Autolayout - Jefferey
KKBOX WWDC17 Notification and Autolayout - Jefferey
KKBOX WWDC17 Airplay 2 - Dolphin
KKBOX WWDC17 Airplay 2 - Dolphin
KKBOX WWDC17 Core Image - Daniel Tien
KKBOX WWDC17 Core Image - Daniel Tien
Auto Layout part 1
Auto Layout part 1
iOS Unit test getting stared
iOS Unit test getting stared
Continuous Integration
Continuous Integration
iOS Design to Code - Code
iOS Design to Code - Code
iOS Design to Code - Design
iOS Design to Code - Design
Beta testing with CI
Beta testing with CI
PTTHOT x IDEAS_HACKATHON 2014
PTTHOT x IDEAS_HACKATHON 2014
選擇
選擇
Recently uploaded
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
soniya singh
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
Tier1 app
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
kzayra69
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
Dinusha Kumarasiri
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
stazi3110
Professional Resume Template for Software Developers
Professional Resume Template for Software Developers
Vinodh Ram
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
kotipi9215
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Christina Lin
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
StefanoLambiase
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
Hr365.us smith
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Ahmed Mohamed
MYjobs Presentation Django-based project
MYjobs Presentation Django-based project
AnoyGreter
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
AxelRicardoTrocheRiq
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
VICTOR MAESTRE RAMIREZ
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
Velvetech LLC
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
Alina Yurenko
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
OPEN KNOWLEDGE GmbH
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
Christina Lin
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
Power Karaoke
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
OnePlan Solutions
Recently uploaded
(20)
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Professional Resume Template for Software Developers
Professional Resume Template for Software Developers
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
MYjobs Presentation Django-based project
MYjobs Presentation Django-based project
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
iOS Unit Testing - Break Dependencies with Protocols, Dummies, and Mocks
1.
iOS Unit testing II Liyao
Chen @ KKBOX
2.
Outlines • External dependency •
透過 Protocol 依賴注⼊入解套 • 透過隔離框架解套
3.
External dependency
4.
–Roy Osherove 是系統中的⼀一個對象, 被測試的程式碼會與其互動,但是你不能控制它。 External dependency (⾦金迎
譯)
5.
External dependency (
6.
External dependency 你跟著師⽗父去幫別⼈人佈線安裝電燈,師⽗父三兩下 就搞定了,然後請你確認有沒有裝好,請問你會 怎麼做? 打開開關看看電燈有沒有跟著亮 再關上開關看電燈有沒有跟著暗
7.
External dependency ⼀一個⽉月後客⼾戶打來說電燈打不開,請你們去檢 查,你第⼀一時間會想到的問題是什麼? 可能開關壞掉了? 可能電線沒接好? 可能電線壞掉了?
8.
External dependency 可能電線壞掉了? 可能開關壞掉了? 可能電線沒接好?
9.
External dependency
10.
External dependency static NSTimeInterval
const yearInterval = 60*60*24*30*12; @interface LCWire () @property (strong, nonatomic) NSDate *expiryDate; @end @implementation LCWire - (instancetype)init { if(self = [super init]){ // 製造⽇日期為 2010/10/10 NSDateComponents *comps = [[NSDateComponents alloc] init]; [comps setDay:10]; [comps setMonth:10]; [comps setYear:2010]; NSDate *manufacturedDate = [[NSCalendar currentCalendar] dateFromComponents:comps]; // 有效期限為兩年 _expiryDate = [manufacturedDate dateByAddingTimeInterval:yearInterval*2]; } return self; } - (BOOL)isExpired { return [[NSDate date] timeIntervalSinceReferenceDate] > [self.expiryDate timeIntervalSinceReferenceDate]; } @end
11.
Break dependency
12.
Break dependency Dummy class Fake
13.
Dummy class A class
that implements an interface but contains fixed data and no logic. – Sangdol
14.
Dummy class DEMO 1. Extract
protocol 2. Use protocol injection 3. Dummy class
15.
Dummy class // LCWire.h @protocol
Expirable <NSObject> - (BOOL)isExpired; @end @interface LCWire : NSObject <Expirable> - (BOOL)isExpired; @end // LCRoomTests.m // 永遠不會過期的電線 @interface LCNeverExpiredWire : NSObject <Expirable> @end @implementation LCNeverExpiredWire - (BOOL)isExpired { return NO; } @end @interface LCRoomTests : XCTestCase @end @implementation LCRoomTests - (void)testLightOnInit { id<Expirable> wire = [[LCNeverExpiredWire alloc] init]; LCRoom *room = [[LCRoom alloc] initWithLight:YES wire:wire]; XCTAssertTrue(room.isLight); } @end
16.
Dummy class - (void)testLightOnInit { LCWire
*wire = [[LCWire alloc] init]; LCRoom *room = [[LCRoom alloc] initWithLight:YES wire:wire]; XCTAssertTrue(room.isLight); } - (void)testLightOnInit { id<Expirable> wire = [[LCNeverExpiredWire alloc] init]; LCRoom *room = [[LCRoom alloc] initWithLight:YES wire:wire]; XCTAssertTrue(room.isLight); }
17.
Dummy class
18.
Break dependency 那那些不能透過軟體設 計控制的怎麼辦?
19.
Break dependency Mock OCMock
20.
Mock object
21.
Mock - PartialMock() -
(void)testLightOnInit { // Mock ⼀一個永遠不會過期的電線 LCWire *wire = [[LCWire alloc] init]; id mockWire = OCMPartialMock(wire); OCMStub([mockWire isExpired]).andReturn(NO); LCRoom *room = [[LCRoom alloc] initWithLight:YES wire:wire]; XCTAssertTrue(room.isLight); }
22.
Mock 1. Mock [NSDate
date] 2. Mock [NSUserDefault standardDefault] 3. Mock session 4. Mock different user in a test case
23.
Mock singleton - (void)testMockDate { NSDate
*now = [NSDate date]; NSDateComponents *comps = [[NSDateComponents alloc] init]; [comps setDay:10]; [comps setMonth:10]; [comps setYear:2010]; NSDate *speficDate = [[NSCalendar currentCalendar] dateFromComponents:comps]; id mockDate = OCMClassMock([NSDate class]); OCMStub([mockDate date]).andReturn(speficDate); // Mock [NSDate date] 讓他回傳指定⽇日期, 也就是 Mock 現在時間 NSLog(@"now: %@, mockDate: %@",now, [NSDate date]); } - (void)testMockUserdefault { NSString *name = [[NSUserDefaults standardUserDefaults] objectForKey:@"userName"]; id mockUserDefault = OCMPartialMock([NSUserDefaults standardUserDefaults]); OCMStub([mockUserDefault objectForKey:@"userName"]).andReturn(@"Liyao Chen"); NSString *mockName = [[NSUserDefaults standardUserDefaults] objectForKey:@"userName"]; NSLog(@"name: %@, mockName: %@", name, mockName); }
24.
Summary • 發現程式缺陷才能解決 • 善⽤用依賴注⼊入改善程式架構 •
當測試有多個Mock時重新檢視設計
25.
QnA • API測試不是後端的⼯工作嗎? • 什麼東⻄西⼀一定要測?
26.
We are hiring! @
KKBOX
27.
Reference • http://stackoverflow.com/questions/346372/ whats-the-difference-between-faking-mocking- and-stubbing
28.
Other links • Sample
code https://github.com/gliyao/LCUnitTestsExample
Download now