SlideShare a Scribd company logo
iOS Testing
Derrick Chao @ Loopd
Frameworks
• XCTest
• OCMock
• KIF
XCTest
• XCTest is the testing framework in Xcode
• A test method is an instance method of a
test class that begins with the prefix test

- (void)testExample {
// This is an example of a functional test case.
XCTAssert(YES, @"Pass");
XCTAssert(1+1==2);
XCTAssertTrue(1+1==2);
XCTAssertFalse(1+1==3);
}
• XCTAssert
XCTAssert(expression, …);
XCTAssertTrue(expression, …);
XCTAssertFalse(expression, ...);
Unit Test Example
- (void)testValidatePassword {
NSString *password1 = @"AbCd1234";
NSString *password2 = @"AbCd12";
NSString *password3 = @"ABCD";
NSString *password4 = @"AbCd1";
NSString *password5 = @"";
XCTAssertTrue([Helper validatePassword:password1]);
XCTAssertTrue([Helper validatePassword:password2]);
XCTAssertFalse([Helper validatePassword:password3]);
XCTAssertFalse([Helper validatePassword:password4]);
XCTAssertFalse([Helper validatePassword:password5]);
}
Test Async Function
Example
• send a message to another user
• async
• block callback
Test Async Function
Example
- (void)testSendMessageWithNilMessage {
XCTestExpectation *expectation =
[self expectationWithDescription:@"completion should be called"];
[Message sendMessage:nil recipientInfo:nil completion:^(id responseObject, NSError
*error) {
[expectation fulfill];
XCTAssertNotNil(error);
XCTAssert([error.userInfo[@"message"] isEqualToString:@"message can't be
nil"]);
}];
[self waitForExpectationsWithTimeout:2 handler:nil];
}
Singleton
// LoopdManager.h file
+ (instancetype)sharedManager;
// LoopdManager.m file
+ (instancetype)sharedManager {
static dispatch_once_t onceToken;
static LoopdManager *sharedInstance;
dispatch_once(&onceToken, ^{
sharedInstance = [[LoopdManager alloc] init];
});
return sharedInstance;
}
Test Singleton Example
- (void)testSharedManager {
LoopdManager *manager1 = [LoopdManager sharedManager];
LoopdManager *manager2 = [LoopdManager sharedManager];
LoopdManager *manager3 = [LoopdManager new];
XCTAssertNotNil(manager1);
XCTAssertNotNil(manager2);
XCTAssertEqual(manager1, manager2);
XCTAssertNotEqual(manager1, manager3);
}
OCMock
• mock objects are simulated objects that mimic the
behavior of real objects in controlled ways

- (void)testMock {
id mockUserInfo = OCMClassMock([UserInfo class]);
// fullname should be nil for now
XCTAssertNil([mockUserInfo fullname]);
// make a custom return value
OCMStub([mockUserInfo fullname]).andReturn(@"David");
// fullname should be David now
XCTAssert([[mockUserInfo fullname] isEqualToString:@"David"]);
}
OCMock Example (1)
ListViewController has a collection view
find all SomeModel from server when viewDidLoad
// in SomeModel.h file

@interface SomeModel : ModelObject
+ (void)findAllByCurrentUserId:(NSString *)currentUserId
completion:(ArrayResultBlock)completion;
@end
OCMock Example (2)
- (void)testCollectionViewCellNumber {
id mockSomeModel = OCMClassMock([SomeModel class]);
OCMStub([mockSomeModel findAllRelationshipsByCurrentUserId:[OCMArg any]
completion:[OCMArg
any]]).andDo(^(NSInvocation *invocation) {
ArrayResultBlock completion;
[invocation getArgument:&completion atIndex: 3];
NSArray *someModels = @[@“1”, @“2”, @“3”, @“4”, @“5”];
completion(someModels, nil);
});
ListViewController *listVC = [ListViewController new];
listVC.view;
NSInteger num = [listVC collectionView:nil numberOfItemsInSection:0];
XCTAssert(num == 5);
XCTAssert(num != 6);
}
KIF
• KIF iOS Integration Testing Framework


KIF Example
@interface UITests : KIFTestCase
@end
@implementation UITests
- (void)testLoginSteps {
[tester tapViewWithAccessibilityLabel:@"regular_button"];
[tester enterText:@"123@123.com" intoViewWithAccessibilityLabel:@"emailTextField"];
[tester enterText:@"abcdefg" intoViewWithAccessibilityLabel:@"passwordTextField"];
[tester tapViewWithAccessibilityLabel:@“checkmark_button"];
}
@end
MVC & MVP
MVC
• view can retrieve data
from model directly
• view hosts all the UI
controls
• high coupling
MVC & MVP
MVP
• MVP is a derivation of the
MVC architectural pattern
• view can’t retrieve data from
model directly
• low coupling
MVP's advantage
• easier to unit test, clean
separation of the View and Model
• maintainability of UI increases
due to almost no dependency on
business logic
• Usually view to presenter map
one to one. Complex views may
have multi presenters
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
cellForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *cell = [collectionView
dequeueReusableCellWithReuseIdentifier:@"Cell"
forIndexPath:indexPath];
// config cell
Car *car = self.cars[indexPath.item];
cell.makeLabel.text = car.make;
cell.modelLabel.text = car.model;
cell.yearLabel.text = car.year;
cell.detailLabel.text = car.detail;
return cell;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
cellForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *cell = [collectionView
dequeueReusableCellWithReuseIdentifier:@"Cell"
forIndexPath:indexPath];
// config cell
Car *car = self.cars[indexPath.item];
cell.car = car;
[cell showUI];
return cell;
}
Test Cell
- (void)testCollectionViewCellNumber {
id mockSomeModel = OCMClassMock([SomeModel class]);
OCMStub([mockSomeModel findAllRelationshipsByCurrentUserId:[OCMArg any]
completion:[OCMArg
any]]).andDo(^(NSInvocation *invocation) {
ArrayResultBlock completion;
[invocation getArgument:&completion atIndex: 3];
NSArray *someModels = @[mod1, mod2, mod3, mod4, mod5];
completion(someModels, nil);
});
ListViewController *listVC = [ListViewController new];
listVC.view;
NSInteger num = [listVC collectionView:nil numberOfItemsInSection:0];
XCTAssert(num == 5);
XCTAssert(num != 6);
UICollectionViewCell *cell = [contactListVC collectionView:nil
cellForItemAtIndexPath:0];
}
Spike Solution
Spike Solution
• not sure how to achieve some
requirement.
Spike Solution (2)
• A spike solution is dirty and quick.
Code just enough to get the answer
you need.
• Throw it away when you’re done with
it.
Spike Solution (3)
• open a new branch
• do some test in the branch
• Throw it away when you’re done with
it
TDD with Xcode
• requirement: a helper for add two
integers
TDD with Xcode (2)
• create files
TDD with Xcode (3)
TDD with Xcode (4)
• command+u
TDD with Xcode (5)
• verify the function
TDD with Xcode (6)
• finish the function then test again
how I feel for TDD at
beginning
benefits of Testing/TDD
• test => spec
• saves you development time
• saves you development time
• Good unit testing forces good
architecture.  In order to make your
code unit-testable, it must be properly
modularized, by writing the unit
testing first various architectural
problems tend to surface earlier
The End
references
• http://iosunittesting.com
• http://stackoverflow.com/questions/
1053406/why-does-apple-say-iphone-
apps-use-mvc
• http://blog.sanc.idv.tw/2011/09/uimvp-
passive-view.html

More Related Content

What's hot

Server1
Server1Server1
Server1
FahriIrawan3
 
The zen of async: Best practices for best performance
The zen of async: Best practices for best performanceThe zen of async: Best practices for best performance
The zen of async: Best practices for best performance
Microsoft Developer Network (MSDN) - Belgium and Luxembourg
 
201913046 wahyu septiansyah network programing
201913046 wahyu septiansyah network programing201913046 wahyu septiansyah network programing
201913046 wahyu septiansyah network programing
wahyuseptiansyah
 
Introduction to Unit Testing (Part 2 of 2)
Introduction to Unit Testing (Part 2 of 2)Introduction to Unit Testing (Part 2 of 2)
Introduction to Unit Testing (Part 2 of 2)
Dennis Byrne
 
Обзор фреймворка Twisted
Обзор фреймворка TwistedОбзор фреймворка Twisted
Обзор фреймворка Twisted
Maxim Kulsha
 
The Ring programming language version 1.6 book - Part 29 of 189
The Ring programming language version 1.6 book - Part 29 of 189The Ring programming language version 1.6 book - Part 29 of 189
The Ring programming language version 1.6 book - Part 29 of 189
Mahmoud Samir Fayed
 
Exception Handling in Scala
Exception Handling in ScalaException Handling in Scala
Exception Handling in Scala
Nag Arvind Gudiseva
 
NodeUkraine - Postgresql для хипстеров или почему ваш следующий проект должен...
NodeUkraine - Postgresql для хипстеров или почему ваш следующий проект должен...NodeUkraine - Postgresql для хипстеров или почему ваш следующий проект должен...
NodeUkraine - Postgresql для хипстеров или почему ваш следующий проект должен...
DmitryChirkin1
 
Down to Stack Traces, up from Heap Dumps
Down to Stack Traces, up from Heap DumpsDown to Stack Traces, up from Heap Dumps
Down to Stack Traces, up from Heap Dumps
Andrei Pangin
 
Spock framework
Spock frameworkSpock framework
Spock framework
Djair Carvalho
 
Andriy Slobodyanyk "How to Use Hibernate: Key Problems and Solutions"
Andriy Slobodyanyk "How to Use Hibernate: Key Problems and Solutions"Andriy Slobodyanyk "How to Use Hibernate: Key Problems and Solutions"
Andriy Slobodyanyk "How to Use Hibernate: Key Problems and Solutions"
LogeekNightUkraine
 
Spockを使おう!
Spockを使おう!Spockを使おう!
Spockを使おう!
Takuma Watabiki
 
#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"
#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"
#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"
epamspb
 
ES3-2020-07 Testing techniques
ES3-2020-07 Testing techniquesES3-2020-07 Testing techniques
ES3-2020-07 Testing techniques
David Rodenas
 
Writing beautiful code with Java 8
Writing beautiful code with Java 8Writing beautiful code with Java 8
Writing beautiful code with Java 8
Sergiu Mircea Indrie
 
V8
V8V8
Javascript Execution Context Flow
Javascript Execution Context FlowJavascript Execution Context Flow
Javascript Execution Context Flow
kang taehun
 
Cascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the StreamsCascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the Streams
mattpodwysocki
 
Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012
Anton Arhipov
 
Everything you wanted to know about Stack Traces and Heap Dumps
Everything you wanted to know about Stack Traces and Heap DumpsEverything you wanted to know about Stack Traces and Heap Dumps
Everything you wanted to know about Stack Traces and Heap Dumps
Andrei Pangin
 

What's hot (20)

Server1
Server1Server1
Server1
 
The zen of async: Best practices for best performance
The zen of async: Best practices for best performanceThe zen of async: Best practices for best performance
The zen of async: Best practices for best performance
 
201913046 wahyu septiansyah network programing
201913046 wahyu septiansyah network programing201913046 wahyu septiansyah network programing
201913046 wahyu septiansyah network programing
 
Introduction to Unit Testing (Part 2 of 2)
Introduction to Unit Testing (Part 2 of 2)Introduction to Unit Testing (Part 2 of 2)
Introduction to Unit Testing (Part 2 of 2)
 
Обзор фреймворка Twisted
Обзор фреймворка TwistedОбзор фреймворка Twisted
Обзор фреймворка Twisted
 
The Ring programming language version 1.6 book - Part 29 of 189
The Ring programming language version 1.6 book - Part 29 of 189The Ring programming language version 1.6 book - Part 29 of 189
The Ring programming language version 1.6 book - Part 29 of 189
 
Exception Handling in Scala
Exception Handling in ScalaException Handling in Scala
Exception Handling in Scala
 
NodeUkraine - Postgresql для хипстеров или почему ваш следующий проект должен...
NodeUkraine - Postgresql для хипстеров или почему ваш следующий проект должен...NodeUkraine - Postgresql для хипстеров или почему ваш следующий проект должен...
NodeUkraine - Postgresql для хипстеров или почему ваш следующий проект должен...
 
Down to Stack Traces, up from Heap Dumps
Down to Stack Traces, up from Heap DumpsDown to Stack Traces, up from Heap Dumps
Down to Stack Traces, up from Heap Dumps
 
Spock framework
Spock frameworkSpock framework
Spock framework
 
Andriy Slobodyanyk "How to Use Hibernate: Key Problems and Solutions"
Andriy Slobodyanyk "How to Use Hibernate: Key Problems and Solutions"Andriy Slobodyanyk "How to Use Hibernate: Key Problems and Solutions"
Andriy Slobodyanyk "How to Use Hibernate: Key Problems and Solutions"
 
Spockを使おう!
Spockを使おう!Spockを使おう!
Spockを使おう!
 
#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"
#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"
#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"
 
ES3-2020-07 Testing techniques
ES3-2020-07 Testing techniquesES3-2020-07 Testing techniques
ES3-2020-07 Testing techniques
 
Writing beautiful code with Java 8
Writing beautiful code with Java 8Writing beautiful code with Java 8
Writing beautiful code with Java 8
 
V8
V8V8
V8
 
Javascript Execution Context Flow
Javascript Execution Context FlowJavascript Execution Context Flow
Javascript Execution Context Flow
 
Cascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the StreamsCascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the Streams
 
Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012
 
Everything you wanted to know about Stack Traces and Heap Dumps
Everything you wanted to know about Stack Traces and Heap DumpsEverything you wanted to know about Stack Traces and Heap Dumps
Everything you wanted to know about Stack Traces and Heap Dumps
 

Similar to Testing (eng)

Unit Testing: Special Cases
Unit Testing: Special CasesUnit Testing: Special Cases
Unit Testing: Special Cases
Ciklum Ukraine
 
Runtime
RuntimeRuntime
Runtime
Jorge Ortiz
 
連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」
matuura_core
 
iOS testing
iOS testingiOS testing
iOS testing
Tomasz Janeczko
 
Agile Iphone Development
Agile Iphone DevelopmentAgile Iphone Development
Agile Iphone Development
Giordano Scalzo
 
Pavel kravchenko obj c runtime
Pavel kravchenko obj c runtimePavel kravchenko obj c runtime
Pavel kravchenko obj c runtime
DneprCiklumEvents
 
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
e-Legion
 
Taking a Test Drive
Taking a Test DriveTaking a Test Drive
Taking a Test Drive
Graham Lee
 
Building stable testing by isolating network layer
Building stable testing by isolating network layerBuilding stable testing by isolating network layer
Building stable testing by isolating network layer
Jz Chang
 
Unit testing patterns for concurrent code
Unit testing patterns for concurrent codeUnit testing patterns for concurrent code
Unit testing patterns for concurrent code
Dror Helper
 
Tdd iPhone For Dummies
Tdd iPhone For DummiesTdd iPhone For Dummies
Tdd iPhone For Dummies
Giordano Scalzo
 
J unit스터디슬라이드
J unit스터디슬라이드J unit스터디슬라이드
J unit스터디슬라이드
ksain
 
openFrameworks 007 - 3D
openFrameworks 007 - 3DopenFrameworks 007 - 3D
openFrameworks 007 - 3D
roxlu
 
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockUnit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Robot Media
 
SQL Server 2005 CLR Integration
SQL Server 2005 CLR IntegrationSQL Server 2005 CLR Integration
SQL Server 2005 CLR Integration
webhostingguy
 
C-Sharp Arithmatic Expression Calculator
C-Sharp Arithmatic Expression CalculatorC-Sharp Arithmatic Expression Calculator
C-Sharp Arithmatic Expression Calculator
Neeraj Kaushik
 
NSOperation objective-c
NSOperation objective-cNSOperation objective-c
NSOperation objective-c
Pavel Albitsky
 
(DEV204) Building High-Performance Native Cloud Apps In C++
(DEV204) Building High-Performance Native Cloud Apps In C++(DEV204) Building High-Performance Native Cloud Apps In C++
(DEV204) Building High-Performance Native Cloud Apps In C++
Amazon Web Services
 
Writing native bindings to node.js in C++
Writing native bindings to node.js in C++Writing native bindings to node.js in C++
Writing native bindings to node.js in C++
nsm.nikhil
 
Objective-c Runtime
Objective-c RuntimeObjective-c Runtime
Objective-c Runtime
Pavel Albitsky
 

Similar to Testing (eng) (20)

Unit Testing: Special Cases
Unit Testing: Special CasesUnit Testing: Special Cases
Unit Testing: Special Cases
 
Runtime
RuntimeRuntime
Runtime
 
連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」
 
iOS testing
iOS testingiOS testing
iOS testing
 
Agile Iphone Development
Agile Iphone DevelopmentAgile Iphone Development
Agile Iphone Development
 
Pavel kravchenko obj c runtime
Pavel kravchenko obj c runtimePavel kravchenko obj c runtime
Pavel kravchenko obj c runtime
 
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
 
Taking a Test Drive
Taking a Test DriveTaking a Test Drive
Taking a Test Drive
 
Building stable testing by isolating network layer
Building stable testing by isolating network layerBuilding stable testing by isolating network layer
Building stable testing by isolating network layer
 
Unit testing patterns for concurrent code
Unit testing patterns for concurrent codeUnit testing patterns for concurrent code
Unit testing patterns for concurrent code
 
Tdd iPhone For Dummies
Tdd iPhone For DummiesTdd iPhone For Dummies
Tdd iPhone For Dummies
 
J unit스터디슬라이드
J unit스터디슬라이드J unit스터디슬라이드
J unit스터디슬라이드
 
openFrameworks 007 - 3D
openFrameworks 007 - 3DopenFrameworks 007 - 3D
openFrameworks 007 - 3D
 
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockUnit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
 
SQL Server 2005 CLR Integration
SQL Server 2005 CLR IntegrationSQL Server 2005 CLR Integration
SQL Server 2005 CLR Integration
 
C-Sharp Arithmatic Expression Calculator
C-Sharp Arithmatic Expression CalculatorC-Sharp Arithmatic Expression Calculator
C-Sharp Arithmatic Expression Calculator
 
NSOperation objective-c
NSOperation objective-cNSOperation objective-c
NSOperation objective-c
 
(DEV204) Building High-Performance Native Cloud Apps In C++
(DEV204) Building High-Performance Native Cloud Apps In C++(DEV204) Building High-Performance Native Cloud Apps In C++
(DEV204) Building High-Performance Native Cloud Apps In C++
 
Writing native bindings to node.js in C++
Writing native bindings to node.js in C++Writing native bindings to node.js in C++
Writing native bindings to node.js in C++
 
Objective-c Runtime
Objective-c RuntimeObjective-c Runtime
Objective-c Runtime
 

Recently uploaded

Wearable antenna for antenna applications
Wearable antenna for antenna applicationsWearable antenna for antenna applications
Wearable antenna for antenna applications
Madhumitha Jayaram
 
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
IJECEIAES
 
A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...
nooriasukmaningtyas
 
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsKuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
Victor Morales
 
ACEP Magazine edition 4th launched on 05.06.2024
ACEP Magazine edition 4th launched on 05.06.2024ACEP Magazine edition 4th launched on 05.06.2024
ACEP Magazine edition 4th launched on 05.06.2024
Rahul
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Christina Lin
 
Technical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prismsTechnical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prisms
heavyhaig
 
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
University of Maribor
 
sieving analysis and results interpretation
sieving analysis and results interpretationsieving analysis and results interpretation
sieving analysis and results interpretation
ssuser36d3051
 
New techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdfNew techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdf
wisnuprabawa3
 
14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application
SyedAbiiAzazi1
 
Swimming pool mechanical components design.pptx
Swimming pool  mechanical components design.pptxSwimming pool  mechanical components design.pptx
Swimming pool mechanical components design.pptx
yokeleetan1
 
Generative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of contentGenerative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of content
Hitesh Mohapatra
 
Modelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdfModelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdf
camseq
 
Embedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoringEmbedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoring
IJECEIAES
 
22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt
KrishnaveniKrishnara1
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
Madan Karki
 
International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...
gerogepatton
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
VICTOR MAESTRE RAMIREZ
 
Manufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptxManufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptx
Madan Karki
 

Recently uploaded (20)

Wearable antenna for antenna applications
Wearable antenna for antenna applicationsWearable antenna for antenna applications
Wearable antenna for antenna applications
 
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
 
A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...
 
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsKuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
 
ACEP Magazine edition 4th launched on 05.06.2024
ACEP Magazine edition 4th launched on 05.06.2024ACEP Magazine edition 4th launched on 05.06.2024
ACEP Magazine edition 4th launched on 05.06.2024
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
 
Technical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prismsTechnical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prisms
 
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
 
sieving analysis and results interpretation
sieving analysis and results interpretationsieving analysis and results interpretation
sieving analysis and results interpretation
 
New techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdfNew techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdf
 
14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application
 
Swimming pool mechanical components design.pptx
Swimming pool  mechanical components design.pptxSwimming pool  mechanical components design.pptx
Swimming pool mechanical components design.pptx
 
Generative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of contentGenerative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of content
 
Modelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdfModelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdf
 
Embedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoringEmbedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoring
 
22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
 
International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
 
Manufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptxManufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptx
 

Testing (eng)

  • 3. XCTest • XCTest is the testing framework in Xcode • A test method is an instance method of a test class that begins with the prefix test
 - (void)testExample { // This is an example of a functional test case. XCTAssert(YES, @"Pass"); XCTAssert(1+1==2); XCTAssertTrue(1+1==2); XCTAssertFalse(1+1==3); } • XCTAssert XCTAssert(expression, …); XCTAssertTrue(expression, …); XCTAssertFalse(expression, ...);
  • 4. Unit Test Example - (void)testValidatePassword { NSString *password1 = @"AbCd1234"; NSString *password2 = @"AbCd12"; NSString *password3 = @"ABCD"; NSString *password4 = @"AbCd1"; NSString *password5 = @""; XCTAssertTrue([Helper validatePassword:password1]); XCTAssertTrue([Helper validatePassword:password2]); XCTAssertFalse([Helper validatePassword:password3]); XCTAssertFalse([Helper validatePassword:password4]); XCTAssertFalse([Helper validatePassword:password5]); }
  • 5. Test Async Function Example • send a message to another user • async • block callback
  • 6. Test Async Function Example - (void)testSendMessageWithNilMessage { XCTestExpectation *expectation = [self expectationWithDescription:@"completion should be called"]; [Message sendMessage:nil recipientInfo:nil completion:^(id responseObject, NSError *error) { [expectation fulfill]; XCTAssertNotNil(error); XCTAssert([error.userInfo[@"message"] isEqualToString:@"message can't be nil"]); }]; [self waitForExpectationsWithTimeout:2 handler:nil]; }
  • 7. Singleton // LoopdManager.h file + (instancetype)sharedManager; // LoopdManager.m file + (instancetype)sharedManager { static dispatch_once_t onceToken; static LoopdManager *sharedInstance; dispatch_once(&onceToken, ^{ sharedInstance = [[LoopdManager alloc] init]; }); return sharedInstance; }
  • 8. Test Singleton Example - (void)testSharedManager { LoopdManager *manager1 = [LoopdManager sharedManager]; LoopdManager *manager2 = [LoopdManager sharedManager]; LoopdManager *manager3 = [LoopdManager new]; XCTAssertNotNil(manager1); XCTAssertNotNil(manager2); XCTAssertEqual(manager1, manager2); XCTAssertNotEqual(manager1, manager3); }
  • 9. OCMock • mock objects are simulated objects that mimic the behavior of real objects in controlled ways
 - (void)testMock { id mockUserInfo = OCMClassMock([UserInfo class]); // fullname should be nil for now XCTAssertNil([mockUserInfo fullname]); // make a custom return value OCMStub([mockUserInfo fullname]).andReturn(@"David"); // fullname should be David now XCTAssert([[mockUserInfo fullname] isEqualToString:@"David"]); }
  • 10. OCMock Example (1) ListViewController has a collection view find all SomeModel from server when viewDidLoad // in SomeModel.h file
 @interface SomeModel : ModelObject + (void)findAllByCurrentUserId:(NSString *)currentUserId completion:(ArrayResultBlock)completion; @end
  • 11. OCMock Example (2) - (void)testCollectionViewCellNumber { id mockSomeModel = OCMClassMock([SomeModel class]); OCMStub([mockSomeModel findAllRelationshipsByCurrentUserId:[OCMArg any] completion:[OCMArg any]]).andDo(^(NSInvocation *invocation) { ArrayResultBlock completion; [invocation getArgument:&completion atIndex: 3]; NSArray *someModels = @[@“1”, @“2”, @“3”, @“4”, @“5”]; completion(someModels, nil); }); ListViewController *listVC = [ListViewController new]; listVC.view; NSInteger num = [listVC collectionView:nil numberOfItemsInSection:0]; XCTAssert(num == 5); XCTAssert(num != 6); }
  • 12. KIF • KIF iOS Integration Testing Framework 

  • 13.
  • 14. KIF Example @interface UITests : KIFTestCase @end @implementation UITests - (void)testLoginSteps { [tester tapViewWithAccessibilityLabel:@"regular_button"]; [tester enterText:@"123@123.com" intoViewWithAccessibilityLabel:@"emailTextField"]; [tester enterText:@"abcdefg" intoViewWithAccessibilityLabel:@"passwordTextField"]; [tester tapViewWithAccessibilityLabel:@“checkmark_button"]; } @end
  • 16. MVC • view can retrieve data from model directly • view hosts all the UI controls • high coupling
  • 18. MVP • MVP is a derivation of the MVC architectural pattern • view can’t retrieve data from model directly • low coupling
  • 19. MVP's advantage • easier to unit test, clean separation of the View and Model • maintainability of UI increases due to almost no dependency on business logic • Usually view to presenter map one to one. Complex views may have multi presenters
  • 20. - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath]; // config cell Car *car = self.cars[indexPath.item]; cell.makeLabel.text = car.make; cell.modelLabel.text = car.model; cell.yearLabel.text = car.year; cell.detailLabel.text = car.detail; return cell; }
  • 21. - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath]; // config cell Car *car = self.cars[indexPath.item]; cell.car = car; [cell showUI]; return cell; }
  • 22.
  • 23. Test Cell - (void)testCollectionViewCellNumber { id mockSomeModel = OCMClassMock([SomeModel class]); OCMStub([mockSomeModel findAllRelationshipsByCurrentUserId:[OCMArg any] completion:[OCMArg any]]).andDo(^(NSInvocation *invocation) { ArrayResultBlock completion; [invocation getArgument:&completion atIndex: 3]; NSArray *someModels = @[mod1, mod2, mod3, mod4, mod5]; completion(someModels, nil); }); ListViewController *listVC = [ListViewController new]; listVC.view; NSInteger num = [listVC collectionView:nil numberOfItemsInSection:0]; XCTAssert(num == 5); XCTAssert(num != 6); UICollectionViewCell *cell = [contactListVC collectionView:nil cellForItemAtIndexPath:0]; }
  • 24.
  • 25.
  • 27. Spike Solution • not sure how to achieve some requirement.
  • 28. Spike Solution (2) • A spike solution is dirty and quick. Code just enough to get the answer you need. • Throw it away when you’re done with it.
  • 29. Spike Solution (3) • open a new branch • do some test in the branch • Throw it away when you’re done with it
  • 30. TDD with Xcode • requirement: a helper for add two integers
  • 31. TDD with Xcode (2) • create files
  • 33. TDD with Xcode (4) • command+u
  • 34. TDD with Xcode (5) • verify the function
  • 35. TDD with Xcode (6) • finish the function then test again
  • 36. how I feel for TDD at beginning
  • 37. benefits of Testing/TDD • test => spec • saves you development time • saves you development time • Good unit testing forces good architecture.  In order to make your code unit-testable, it must be properly modularized, by writing the unit testing first various architectural problems tend to surface earlier