SlideShare ist ein Scribd-Unternehmen logo
1 von 84
Downloaden Sie, um offline zu lesen
Unit Testing
Unit Testing
What Is Testing For? 
Unit Testing
When Should Software Be Tested?
What Is Testing For? 
What Is Testing For?
What Is Testing For?
Testing can show that the product works!
When Should Software
Be Tested?
Waterfall project management process
Waterfall project management process

Requirements
Waterfall project management process

Requirements
Specification
Waterfall project management process

Requirements
Development
Specification
Waterfall project management process

Requirements
Test
Development
Specification
Waterfall project management process

Requirements
Test
Development
Specification
Deployment
Cost of Bugs Time Detected
Time
Introduced
Requirements Architecture Coding System Test
Post-

Release
Requirements 1 3 5-10 10 10-100
Architecture - 1 10 15 25-100
Coding - - 1 10 10-25
Cost of Fixing Bugs Found at Different Stages of
the Software Development Process
When Should Software
Be Tested?
When Should Software
Be Tested?
Software should be tested all the time!
Unit Testing
What is Unit Test?
Unit tests are small pieces of code that
test the behavior of other code.
A test is not a unit test if:
• It talks to the database

• It communicates across the network

• It touches the file system

• It can't run at the same time as any of your
other unit tests

• You have to do special things to your environment
(such as editing config files) to run it.
Properties of a Good
Unit Test
A good unit test:
is able to be fully automated
A good unit test:
Tests a single logical concept in the system
A good unit test:
Consistently returns the same result (no
random numbers, save those for integration
tests)
A good unit test:
is Maintainable and order-independent
A good unit test:
is Independent
A good unit test:
Runs fast
A good unit test:
is Readable
A good unit test:
is Trustworthy (when you see its result, you
don’t need to debug the code just to be sure)
A good unit test is:
• Able to be fully automated

• Tests a single logical concept in the system

• Consistently returns the same result

• Maintainable and order-independent

• Independent

• Runs fast

• Readable

• Trustworthy
Verifications
Types of Verifications
•Return Value

•State

•Behavior
Types of Verifications
SUT
Types of Verifications
SUT
Behavior 

(Indirect

Outputs)
DOC
Types of Verifications
SUTSetup
Exercise
Verify
Tear Down
Behavior 

(Indirect

Outputs)
DOC
Return Value Verification
We inspect the value returned from the
system under test and compare it to the
expected state.
SUTSetup
Exercise
Verify
Tear Down
Behavior 

(Indirect

Outputs)
DOC
State Verification
We inspect the state of the system under
test after it has been exercised and compare
it to the expected state.
SUTSetup
Exercise
Verify
Tear Down
Behavior 

(Indirect

Outputs)
DOC
State
SUT
Behavior Verification
We capture the indirect outputs of the SUT
as they occur and compare them to the
expected behavior.
Setup
Exercise
Verify
Tear Down
Behavior 

(Indirect

Outputs)
DOC
SUT
Behavior Verification
We capture the indirect outputs of the SUT
as they occur and compare them to the
expected behavior.
Setup
Exercise
Verify
Tear Down
Behavior 

(Indirect

Outputs)
Fake
Verify
XCTest
XCTest
• Provided by Xcode
XCTest
• Provided by Xcode

• New iOS application projects automatically include a unit
testing target
XCTest
• Provided by Xcode

• New iOS application projects automatically include a unit
testing target

• Test classes do not have a header file
XCTest
• Provided by Xcode

• New iOS application projects automatically include a unit
testing target

• Test classes do not have a header file

• It’s not necessary to add application’s source files to the
XCTest Target
XCTest
• Provided by Xcode

• New iOS application projects automatically include a unit
testing target

• Test classes do not have a header file

• It’s not necessary to add application’s source files to the
XCTest Target

• Each test case is a method with prefix test
XCTest
• Provided by Xcode

• New iOS application projects automatically include a unit
testing target

• Test classes do not have a header file

• It’s not necessary to add application’s source files to the
XCTest Target

• Each test case is a method with prefix test

• Xcode 5 allows to run tests from the editor
XCTest Flow
Setup Tear DownTest
- (void)setUp
{
[super setUp];
// This method is called before the invocation of each test method in the class.
}
!
- (void)tearDown
{
// This method is called after the invocation of each test method in the class.
[super tearDown];
}
!
- (void)testExample
{
XCTFail(@"No implementation for "%s"", __PRETTY_FUNCTION__);
}
Test main actions:
• Arrange objects, creating and setting them up as necessary. 

• Act on an object. 

• Assert that something is as expected.
!
- (void)testMakeConversionWithModeMilesToKilometers
{
// Arrange
sut.value = @(1);
// Act
[sut makeConversionWithMode:ConverterModeMilesToKm];
// Assert
XCTAssertTrue([sut.text isEqualToString:@"1.609344"], @"should convert from
miles to kilometers");
}
@interface ConverterModelTests : XCTestCase
{
ConverterModel* sut;
}
@end
!
@implementation ConverterModelTests
!
- (void)setUp
{
[super setUp];
sut = [ConverterModel new];
}
!
- (void)tearDown
{
sut = nil;
[super tearDown];
}
!
- (void)testMakeConversionWithModeMilesToKilometers
{
// Arrange
sut.value = @(1);
// Act
[sut makeConversionWithMode:ConverterModeMilesToKm];
// Assert
XCTAssertTrue([sut.text isEqualToString:@"1.609344"], @"should convert from miles to
kilometers");
}
!
@end
XCTest Asserts
• XCTFail (format…)
• XCTAssertNil (a1, format…)
• XCTAssertNotNil (a1, format…)
• XCTAssert (a1, format…)
• XCTAssertTrue (a1, format…)
• XCTAssertFalse (a1, format…)
• XCTAssertEqualObjects (a1, a2, format…)
• XCTAssertEquals (a1, a2, format…)
• XCTAssertEqualsWithAccuracy (a1, a2, accuracy, format…)
• XCTAssertThrows (expression, format…)
• XCTAssertThrowsSpecific (expression, exception, format…)
• XCTAssertThrowsSpecificNamed (expression, exception, name, format…)
• XCTAssertNoThrow (expression, format…)
• XCTAssertNoThrowSpecific (expression, exception, format…)
• XCTAssertNoThrowSpecificNamed (expression, exception, name, format…)
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(someAction:)
name:kSomeNotification
object:nil];
}
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(someAction:)
name:kSomeNotification
object:nil];
}
- (void)testViewDidLoadAddsObserverForSomeNotification
{
// Arrange
// Act
// Assert
!
}
Dependency Injection
Dependency Injection
is a software design pattern that
implements passing a service to a client,
rather than allowing a client to build or
find the service.
Constructor Injection
the dependencies are provided through a
class constructor
- (id)initWithNotificationCenter:(NSNotificationCenter *)notificationCenter
Setter Injection
the client exposes a setter method that the
injector uses to inject the dependency
@property (nonatomic, weak) NSUserDefaults* userDefaults;
Dependency Injection
providing an instance variable for dependency
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(someAction:)
name:kSomeNotification
object:nil];
}
Dependency
- (void)testViewDidLoadAddsObserverForSomeNotification
{
// Arrange
// Act
// Assert
!
}
- (id)initWithNotificationCenter:(NSNotificationCenter *)notificationCenter
{
self = [super init];
if(self)
{
_notificationCenter = notificationCenter;
}
return self;
}
!
!
- (void)viewDidLoad
{
[super viewDidLoad];
[_notificationCenter addObserver:self
selector:@selector(someAction:)
name:kSomeNotification
object:nil];
}
Inject Dependency
Mocks
is a fake object in the system that verifies the
object under test interacted as expected with
the fake object.
Mock Object
It is common in unit tests to mock or stub
collaborators of the system under test so that the
test is independent of the implementation of the
collaborators.
Mock Object
SUT
Behavior Verification
Setup
Exercise
Verify
Tear Down
Behavior 

(Indirect

Outputs)
Fake
Verify
Test
Mocks
SUT communicates with the mock object, and all
communication is recorded in the mock. The test
uses the mock to verify that the test passes.
SUT Mock
Communicate
Assert
Test
Stubs
Returns specified result for a message, stubs
can’t fail the test.
SUT Stub
Communicate
Assert
@interface ConverterViewController : UIViewController
!
@property (nonatomic, weak) NSNotificationCenter* notificationCenter;
!
@end
!
!
@implementation ConverterViewController
!
- (void)viewDidLoad
{
[super viewDidLoad];
[_notificationCenter addObserver:self
selector:@selector(someAction:)
name:kSomeNotification
object:nil];
}
!
@end
Injected Dependency
@interface ConverterViewController : UIViewController
!
@property (nonatomic, weak) NSNotificationCenter* notificationCenter;
!
@end
!
!
@implementation ConverterViewController
!
- (void)viewDidLoad
{
[super viewDidLoad];
[_notificationCenter addObserver:self
selector:@selector(someAction:)
name:kSomeNotification
object:nil];
}
!
@end
Injected Dependency
Replace with a mock
What we need?
•an object that responds to
addObserver:selector:name:object:

•possibility to record a call

•check for notification’s name

•verification
@interface FakeNotificationCenter : NSObject
{
BOOL _hasCalled;
}
@property (nonatomic, strong) NSString* expectedName;
!
- (void)addObserver:(id)observer selector:(SEL)aSelector name:(NSString *)aName object:(id)anObject;
- (void)verify;
!
@end
!
!
@implementation FakeNotificationCenter
!
- (void)addObserver:(id)observer selector:(SEL)aSelector name:(NSString *)aName object:(id)anObject
{
_hasCalled = [_expectedName isEqualToString:aName];
}
!
- (void)verify
{
NSAssert(_hasCalled, @"expected method was not called with specified parameters");
}
!
@end
What we can do
- (void)testViewDidLoadAddsObserverForSomeNotification
{
// Arrange
FakeNotificationCenter* fake = [FakeNotificationCenter new];
fake.expectedName = kSomeNotification;
sut.notificationCenter = (id)fake;
// Assert
[fake verify];
}
!
How can we use it?
- (void)testViewDidLoadAddsObserverForSomeNotification
{
// Arrange
FakeNotificationCenter* fake = [FakeNotificationCenter new];
fake.expectedName = kSomeNotification;
sut.notificationCenter = (id)fake;
!
// Assert
[fake verify];
}
!
-[ConverterViewControllerTests testViewDidLoadAddsObserver]
failed: expected method was not called with specified parameters
How can we use it?
- (void)testViewDidLoadAddsObserverForSomeNotification
{
// Arrange
FakeNotificationCenter* fake = [FakeNotificationCenter new];
fake.expectedName = kSomeNotification;
sut.notificationCenter = (id)fake;
!
// Act
[sut viewDidLoad];
// Assert
[fake verify];
}
How can we use it?
OCMock
OCMock Provides
•stub objects that return pre-determined values
for specific method invocations

•dynamic mocks that can be used to verify
interaction patterns

•partial mocks to overwrite selected methods of
existing objects
Mocks
// Creates a mock object that can be used as if it were an instance of
// SomeClass.
id mock = [OCMockObject mockForClass:[SomeClass class]];
!
!
// Tells the mock object that someMethod: should be called with an argument
// that is equal to someArgument.
[[mock expect] someMethod:someArgument];
!
// After this setup the functionality under test should be invoked
// followed by
[mock verify];
!
!
// When a method is called on a mock object that has not been set up with
// either expect or stub the mock object will raise an exception. This
// fail-fast mode can be turned off by creating a "nice" mock:
id mock = [OCMockObject niceMockForClass:[SomeClass class]];
!
// While nice mocks will simply ignore all unexpected methods it is
// possible to disallow specific methods:
[[mock reject] someMethod];
Stubs
// Tells the mock object that when someMethod: is called with
// someArgument it should return aValue.
[[[mock stub] andReturn:aValue] someMethod:someArgument];
!
!
!
// It is not possible to pass primitive types directly.
[[[mock stub] andReturnValue:@YES] aMethodReturnABoolean:someArgument];
!
!
// The mock object can also throw an exception or post a notification
// when a method is called
[[[mock stub] andThrow:anException] someMethod:someArgument];
[[[mock stub] andPost:aNotification] someMethod:someArgument];
!
!
!
// If Objective-C blocks are available a block can be used to handle the
// invocation and set up a return value
void (^theBlock)(NSInvocation *) = ^(NSInvocation *invocation) {
/* code that reads and modifies the invocation object */
};
[[[mock stub] andDo:theBlock] someMethod:[OCMArg any]];
@interface ConverterViewController : UIViewController
!
@property (nonatomic, weak) NSNotificationCenter* notificationCenter;
!
@end
!
!
@implementation ConverterViewController
!
- (void)viewDidLoad
{
[super viewDidLoad];
[_notificationCenter addObserver:self
selector:@selector(someAction:)
name:kSomeNotification
object:nil];
}
!
@end
Injected Dependency
- (void)testViewDidLoadAddsObserver
{
// Arrange
id mock = [OCMockObject mockForClass:[NSNotificationCenter class]];
[[mock expect] addObserver:sut
selector:[OCMArg anySelector]
name:kConverterModelDidUpdateNotification
object:OCMOCK_ANY];
sut.notificationCenter = mock;
!
// Act
[sut viewDidLoad];
// Assert
[mock verify];
}
How we test this with OCMock
Legacy Code?
How to start with Existing Project
• All developers in team must write and run tests
How to start with Existing Project
• All developers in team must write and run tests

• Start with warnings and bugs
How to start with Existing Project
• All developers in team must write and run tests

• Start with warnings and bugs

• Isolate modules and classes
How to start with Existing Project
• All developers in team must write and run tests

• Start with warnings and bugs

• Isolate modules and classes

• Don’t miss refactoring
How to start with Existing Project
• All developers in team must write and run tests

• Start with warnings and bugs

• Isolate modules and classes

• Don’t miss refactoring

• Increase test-coverage step-by-step with new
functionality
Demo Code
https://github.com/maksumko/ConverterApp

!
maksum.ko
Sources
http://www.amazon.com/Art-Unit-Testing-Examples-Net/dp/1933988274

!
http://www.amazon.com/Test-Driven-iOS-Development-Developers-Library/dp/0321774183

!
http://www.amazon.com/Growing-Object-Oriented-Software-Guided-Tests/dp/0321503627 

!
http://martinfowler.com/articles/mocksArentStubs.html
Questions?

Weitere ähnliche Inhalte

Was ist angesagt?

What's software testing
What's software testingWhat's software testing
What's software testingLi-Wei Cheng
 
Unit testing in android
Unit testing in androidUnit testing in android
Unit testing in androidLi-Wei Cheng
 
Qtp Basics
Qtp BasicsQtp Basics
Qtp Basicsmehramit
 
Oh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to MutationOh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to MutationPaul Blundell
 
Software Testing
Software TestingSoftware Testing
Software TestingAdroitLogic
 
TEST_AUTOMATION_CASE_STUDY_(2)2[1]
TEST_AUTOMATION_CASE_STUDY_(2)2[1]TEST_AUTOMATION_CASE_STUDY_(2)2[1]
TEST_AUTOMATION_CASE_STUDY_(2)2[1]Clive Dall
 
The Future is Now: Writing Automated Tests To Grow Your Code
The Future is Now: Writing Automated Tests To Grow Your CodeThe Future is Now: Writing Automated Tests To Grow Your Code
The Future is Now: Writing Automated Tests To Grow Your CodeIsaac Murchie
 
Model-based Testing: Taking BDD/ATDD to the Next Level
Model-based Testing: Taking BDD/ATDD to the Next LevelModel-based Testing: Taking BDD/ATDD to the Next Level
Model-based Testing: Taking BDD/ATDD to the Next LevelBob Binder
 
What is UFT? HP's unified functional testing.
What is UFT? HP's unified functional testing.What is UFT? HP's unified functional testing.
What is UFT? HP's unified functional testing.Confiz
 
Android Test Driven Development
Android Test Driven DevelopmentAndroid Test Driven Development
Android Test Driven DevelopmentArif Huda
 
TDD with Visual Studio 2010
TDD with Visual Studio 2010TDD with Visual Studio 2010
TDD with Visual Studio 2010Stefano Paluello
 
RFT Tutorial - 9 How To Create A Properties Verification Point In Rft For Tes...
RFT Tutorial - 9 How To Create A Properties Verification Point In Rft For Tes...RFT Tutorial - 9 How To Create A Properties Verification Point In Rft For Tes...
RFT Tutorial - 9 How To Create A Properties Verification Point In Rft For Tes...Yogindernath Gupta
 
Writing good unit test
Writing good unit testWriting good unit test
Writing good unit testLucy Lu
 
Efficient JavaScript Unit Testing, March 2013
Efficient JavaScript Unit Testing, March 2013Efficient JavaScript Unit Testing, March 2013
Efficient JavaScript Unit Testing, March 2013Hazem Saleh
 
Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++Hong Le Van
 
Automated testing of ASP .Net Core applications
Automated testing of ASP .Net Core applications Automated testing of ASP .Net Core applications
Automated testing of ASP .Net Core applications nispas
 
Beginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NETBeginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NETBaskar K
 

Was ist angesagt? (20)

What's software testing
What's software testingWhat's software testing
What's software testing
 
Unit testing in android
Unit testing in androidUnit testing in android
Unit testing in android
 
Qtp Basics
Qtp BasicsQtp Basics
Qtp Basics
 
Oh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to MutationOh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to Mutation
 
Software Testing
Software TestingSoftware Testing
Software Testing
 
TEST_AUTOMATION_CASE_STUDY_(2)2[1]
TEST_AUTOMATION_CASE_STUDY_(2)2[1]TEST_AUTOMATION_CASE_STUDY_(2)2[1]
TEST_AUTOMATION_CASE_STUDY_(2)2[1]
 
The Future is Now: Writing Automated Tests To Grow Your Code
The Future is Now: Writing Automated Tests To Grow Your CodeThe Future is Now: Writing Automated Tests To Grow Your Code
The Future is Now: Writing Automated Tests To Grow Your Code
 
Ppt Qtp
Ppt QtpPpt Qtp
Ppt Qtp
 
Model-based Testing: Taking BDD/ATDD to the Next Level
Model-based Testing: Taking BDD/ATDD to the Next LevelModel-based Testing: Taking BDD/ATDD to the Next Level
Model-based Testing: Taking BDD/ATDD to the Next Level
 
Integration testing
Integration testingIntegration testing
Integration testing
 
What is UFT? HP's unified functional testing.
What is UFT? HP's unified functional testing.What is UFT? HP's unified functional testing.
What is UFT? HP's unified functional testing.
 
Android Test Driven Development
Android Test Driven DevelopmentAndroid Test Driven Development
Android Test Driven Development
 
TDD with Visual Studio 2010
TDD with Visual Studio 2010TDD with Visual Studio 2010
TDD with Visual Studio 2010
 
RFT Tutorial - 9 How To Create A Properties Verification Point In Rft For Tes...
RFT Tutorial - 9 How To Create A Properties Verification Point In Rft For Tes...RFT Tutorial - 9 How To Create A Properties Verification Point In Rft For Tes...
RFT Tutorial - 9 How To Create A Properties Verification Point In Rft For Tes...
 
Writing good unit test
Writing good unit testWriting good unit test
Writing good unit test
 
Efficient JavaScript Unit Testing, March 2013
Efficient JavaScript Unit Testing, March 2013Efficient JavaScript Unit Testing, March 2013
Efficient JavaScript Unit Testing, March 2013
 
Testing In Java
Testing In JavaTesting In Java
Testing In Java
 
Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++
 
Automated testing of ASP .Net Core applications
Automated testing of ASP .Net Core applications Automated testing of ASP .Net Core applications
Automated testing of ASP .Net Core applications
 
Beginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NETBeginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NET
 

Ähnlich wie Unit Tesing in iOS

Automated testing overview
Automated testing overviewAutomated testing overview
Automated testing overviewAlex Pop
 
An Introduction to Unit Test Using NUnit
An Introduction to Unit Test Using NUnitAn Introduction to Unit Test Using NUnit
An Introduction to Unit Test Using NUnitweili_at_slideshare
 
DIG1108C Lesson 7 Fall 2014
DIG1108C Lesson 7 Fall 2014DIG1108C Lesson 7 Fall 2014
DIG1108C Lesson 7 Fall 2014David Wolfpaw
 
Unit tests & TDD
Unit tests & TDDUnit tests & TDD
Unit tests & TDDDror Helper
 
Qt test framework
Qt test frameworkQt test framework
Qt test frameworkICS
 
Test Driven Development with JavaFX
Test Driven Development with JavaFXTest Driven Development with JavaFX
Test Driven Development with JavaFXHendrik Ebbers
 
Iasi code camp 20 april 2013 marian chicu - database unit tests in the sql se...
Iasi code camp 20 april 2013 marian chicu - database unit tests in the sql se...Iasi code camp 20 april 2013 marian chicu - database unit tests in the sql se...
Iasi code camp 20 april 2013 marian chicu - database unit tests in the sql se...Codecamp Romania
 
Testing Frameworks
Testing FrameworksTesting Frameworks
Testing FrameworksMoataz Nabil
 
Module V - Software Testing Strategies.pdf
Module V - Software Testing Strategies.pdfModule V - Software Testing Strategies.pdf
Module V - Software Testing Strategies.pdfadhithanr
 
Coldbox developer training – session 4
Coldbox developer training – session 4Coldbox developer training – session 4
Coldbox developer training – session 4Billie Berzinskas
 
Lecture #6. automation testing (andrey oleynik)
Lecture #6. automation testing (andrey oleynik)Lecture #6. automation testing (andrey oleynik)
Lecture #6. automation testing (andrey oleynik)Andrey Oleynik
 
Software Testing interview - Q&A and tips
Software Testing interview - Q&A and tipsSoftware Testing interview - Q&A and tips
Software Testing interview - Q&A and tipsPankaj Dubey
 
Database Unit Testing Made Easy with VSTS
Database Unit Testing Made Easy with VSTSDatabase Unit Testing Made Easy with VSTS
Database Unit Testing Made Easy with VSTSSanil Mhatre
 

Ähnlich wie Unit Tesing in iOS (20)

Testing Angular
Testing AngularTesting Angular
Testing Angular
 
Automated testing overview
Automated testing overviewAutomated testing overview
Automated testing overview
 
An Introduction to Unit Test Using NUnit
An Introduction to Unit Test Using NUnitAn Introduction to Unit Test Using NUnit
An Introduction to Unit Test Using NUnit
 
DIG1108C Lesson 7 Fall 2014
DIG1108C Lesson 7 Fall 2014DIG1108C Lesson 7 Fall 2014
DIG1108C Lesson 7 Fall 2014
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Unit tests & TDD
Unit tests & TDDUnit tests & TDD
Unit tests & TDD
 
Continuous Integration
Continuous IntegrationContinuous Integration
Continuous Integration
 
Qt test framework
Qt test frameworkQt test framework
Qt test framework
 
Unit testing on mobile apps
Unit testing on mobile appsUnit testing on mobile apps
Unit testing on mobile apps
 
Test Driven Development with JavaFX
Test Driven Development with JavaFXTest Driven Development with JavaFX
Test Driven Development with JavaFX
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Iasi code camp 20 april 2013 marian chicu - database unit tests in the sql se...
Iasi code camp 20 april 2013 marian chicu - database unit tests in the sql se...Iasi code camp 20 april 2013 marian chicu - database unit tests in the sql se...
Iasi code camp 20 april 2013 marian chicu - database unit tests in the sql se...
 
Testing Frameworks
Testing FrameworksTesting Frameworks
Testing Frameworks
 
Module V - Software Testing Strategies.pdf
Module V - Software Testing Strategies.pdfModule V - Software Testing Strategies.pdf
Module V - Software Testing Strategies.pdf
 
Coldbox developer training – session 4
Coldbox developer training – session 4Coldbox developer training – session 4
Coldbox developer training – session 4
 
Lecture #6. automation testing (andrey oleynik)
Lecture #6. automation testing (andrey oleynik)Lecture #6. automation testing (andrey oleynik)
Lecture #6. automation testing (andrey oleynik)
 
Software Testing interview - Q&A and tips
Software Testing interview - Q&A and tipsSoftware Testing interview - Q&A and tips
Software Testing interview - Q&A and tips
 
TDD Workshop UTN 2012
TDD Workshop UTN 2012TDD Workshop UTN 2012
TDD Workshop UTN 2012
 
Unit test
Unit testUnit test
Unit test
 
Database Unit Testing Made Easy with VSTS
Database Unit Testing Made Easy with VSTSDatabase Unit Testing Made Easy with VSTS
Database Unit Testing Made Easy with VSTS
 

Mehr von Ciklum Ukraine

"How keep normal blood pressure using TDD" By Roman Loparev
"How keep normal blood pressure using TDD" By Roman Loparev"How keep normal blood pressure using TDD" By Roman Loparev
"How keep normal blood pressure using TDD" By Roman LoparevCiklum Ukraine
 
"Through the three circles of the it hell" by Roman Liashenko
"Through the three circles of the it hell" by Roman Liashenko"Through the three circles of the it hell" by Roman Liashenko
"Through the three circles of the it hell" by Roman LiashenkoCiklum Ukraine
 
Alex Pazhyn: Google_Material_Design
Alex Pazhyn: Google_Material_DesignAlex Pazhyn: Google_Material_Design
Alex Pazhyn: Google_Material_DesignCiklum Ukraine
 
Introduction to amazon web services for developers
Introduction to amazon web services for developersIntroduction to amazon web services for developers
Introduction to amazon web services for developersCiklum Ukraine
 
Your 1st Apple watch Application
Your 1st Apple watch ApplicationYour 1st Apple watch Application
Your 1st Apple watch ApplicationCiklum Ukraine
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven DevelopmentCiklum Ukraine
 
Back to the future: ux trends 2015
Back to the future: ux trends 2015Back to the future: ux trends 2015
Back to the future: ux trends 2015Ciklum Ukraine
 
Developing high load systems using C++
Developing high load systems using C++Developing high load systems using C++
Developing high load systems using C++Ciklum Ukraine
 
Collection view layout
Collection view layoutCollection view layout
Collection view layoutCiklum Ukraine
 
Introduction to auto layout
Introduction to auto layoutIntroduction to auto layout
Introduction to auto layoutCiklum Ukraine
 
Unit Testing: Special Cases
Unit Testing: Special CasesUnit Testing: Special Cases
Unit Testing: Special CasesCiklum Ukraine
 
Model-View-Controller: Tips&Tricks
Model-View-Controller: Tips&TricksModel-View-Controller: Tips&Tricks
Model-View-Controller: Tips&TricksCiklum Ukraine
 
Future of Outsourcing report published in The Times featuring Ciklum's CEO To...
Future of Outsourcing report published in The Times featuring Ciklum's CEO To...Future of Outsourcing report published in The Times featuring Ciklum's CEO To...
Future of Outsourcing report published in The Times featuring Ciklum's CEO To...Ciklum Ukraine
 
Михаил Попчук "Cкрытые резервы команд или 1+1=3"
Михаил Попчук "Cкрытые резервы команд или 1+1=3"Михаил Попчук "Cкрытые резервы команд или 1+1=3"
Михаил Попчук "Cкрытые резервы команд или 1+1=3"Ciklum Ukraine
 
"To be, rather than to seem” interview with Ciklum VP of HR Marina Vyshegorod...
"To be, rather than to seem” interview with Ciklum VP of HR Marina Vyshegorod..."To be, rather than to seem” interview with Ciklum VP of HR Marina Vyshegorod...
"To be, rather than to seem” interview with Ciklum VP of HR Marina Vyshegorod...Ciklum Ukraine
 

Mehr von Ciklum Ukraine (20)

"How keep normal blood pressure using TDD" By Roman Loparev
"How keep normal blood pressure using TDD" By Roman Loparev"How keep normal blood pressure using TDD" By Roman Loparev
"How keep normal blood pressure using TDD" By Roman Loparev
 
"Through the three circles of the it hell" by Roman Liashenko
"Through the three circles of the it hell" by Roman Liashenko"Through the three circles of the it hell" by Roman Liashenko
"Through the three circles of the it hell" by Roman Liashenko
 
Alex Pazhyn: Google_Material_Design
Alex Pazhyn: Google_Material_DesignAlex Pazhyn: Google_Material_Design
Alex Pazhyn: Google_Material_Design
 
Introduction to amazon web services for developers
Introduction to amazon web services for developersIntroduction to amazon web services for developers
Introduction to amazon web services for developers
 
Your 1st Apple watch Application
Your 1st Apple watch ApplicationYour 1st Apple watch Application
Your 1st Apple watch Application
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Back to the future: ux trends 2015
Back to the future: ux trends 2015Back to the future: ux trends 2015
Back to the future: ux trends 2015
 
Developing high load systems using C++
Developing high load systems using C++Developing high load systems using C++
Developing high load systems using C++
 
Collection view layout
Collection view layoutCollection view layout
Collection view layout
 
Introduction to auto layout
Introduction to auto layoutIntroduction to auto layout
Introduction to auto layout
 
Groovy on Android
Groovy on AndroidGroovy on Android
Groovy on Android
 
Unit Testing: Special Cases
Unit Testing: Special CasesUnit Testing: Special Cases
Unit Testing: Special Cases
 
Material design
Material designMaterial design
Material design
 
Kanban development
Kanban developmentKanban development
Kanban development
 
Mobile sketching
Mobile sketching Mobile sketching
Mobile sketching
 
More UX in our life
More UX in our lifeMore UX in our life
More UX in our life
 
Model-View-Controller: Tips&Tricks
Model-View-Controller: Tips&TricksModel-View-Controller: Tips&Tricks
Model-View-Controller: Tips&Tricks
 
Future of Outsourcing report published in The Times featuring Ciklum's CEO To...
Future of Outsourcing report published in The Times featuring Ciklum's CEO To...Future of Outsourcing report published in The Times featuring Ciklum's CEO To...
Future of Outsourcing report published in The Times featuring Ciklum's CEO To...
 
Михаил Попчук "Cкрытые резервы команд или 1+1=3"
Михаил Попчук "Cкрытые резервы команд или 1+1=3"Михаил Попчук "Cкрытые резервы команд или 1+1=3"
Михаил Попчук "Cкрытые резервы команд или 1+1=3"
 
"To be, rather than to seem” interview with Ciklum VP of HR Marina Vyshegorod...
"To be, rather than to seem” interview with Ciklum VP of HR Marina Vyshegorod..."To be, rather than to seem” interview with Ciklum VP of HR Marina Vyshegorod...
"To be, rather than to seem” interview with Ciklum VP of HR Marina Vyshegorod...
 

Kürzlich hochgeladen

How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 

Kürzlich hochgeladen (20)

How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 

Unit Tesing in iOS

  • 2. Unit Testing What Is Testing For? 
  • 3. Unit Testing When Should Software Be Tested? What Is Testing For? 
  • 5. What Is Testing For? Testing can show that the product works!
  • 8. Waterfall project management process Requirements
  • 9. Waterfall project management process Requirements Specification
  • 10. Waterfall project management process Requirements Development Specification
  • 11. Waterfall project management process Requirements Test Development Specification
  • 12. Waterfall project management process Requirements Test Development Specification Deployment
  • 13. Cost of Bugs Time Detected Time Introduced Requirements Architecture Coding System Test Post- Release Requirements 1 3 5-10 10 10-100 Architecture - 1 10 15 25-100 Coding - - 1 10 10-25 Cost of Fixing Bugs Found at Different Stages of the Software Development Process
  • 15. When Should Software Be Tested? Software should be tested all the time!
  • 17. What is Unit Test? Unit tests are small pieces of code that test the behavior of other code.
  • 18. A test is not a unit test if: • It talks to the database • It communicates across the network • It touches the file system • It can't run at the same time as any of your other unit tests • You have to do special things to your environment (such as editing config files) to run it.
  • 19. Properties of a Good Unit Test
  • 20. A good unit test: is able to be fully automated
  • 21. A good unit test: Tests a single logical concept in the system
  • 22. A good unit test: Consistently returns the same result (no random numbers, save those for integration tests)
  • 23. A good unit test: is Maintainable and order-independent
  • 24. A good unit test: is Independent
  • 25. A good unit test: Runs fast
  • 26. A good unit test: is Readable
  • 27. A good unit test: is Trustworthy (when you see its result, you don’t need to debug the code just to be sure)
  • 28. A good unit test is: • Able to be fully automated • Tests a single logical concept in the system • Consistently returns the same result • Maintainable and order-independent • Independent • Runs fast • Readable • Trustworthy
  • 30. Types of Verifications •Return Value •State •Behavior
  • 32. Types of Verifications SUT Behavior (Indirect Outputs) DOC
  • 33. Types of Verifications SUTSetup Exercise Verify Tear Down Behavior (Indirect Outputs) DOC
  • 34. Return Value Verification We inspect the value returned from the system under test and compare it to the expected state. SUTSetup Exercise Verify Tear Down Behavior (Indirect Outputs) DOC
  • 35. State Verification We inspect the state of the system under test after it has been exercised and compare it to the expected state. SUTSetup Exercise Verify Tear Down Behavior (Indirect Outputs) DOC State
  • 36. SUT Behavior Verification We capture the indirect outputs of the SUT as they occur and compare them to the expected behavior. Setup Exercise Verify Tear Down Behavior (Indirect Outputs) DOC
  • 37. SUT Behavior Verification We capture the indirect outputs of the SUT as they occur and compare them to the expected behavior. Setup Exercise Verify Tear Down Behavior (Indirect Outputs) Fake Verify
  • 40. XCTest • Provided by Xcode • New iOS application projects automatically include a unit testing target
  • 41. XCTest • Provided by Xcode • New iOS application projects automatically include a unit testing target • Test classes do not have a header file
  • 42. XCTest • Provided by Xcode • New iOS application projects automatically include a unit testing target • Test classes do not have a header file • It’s not necessary to add application’s source files to the XCTest Target
  • 43. XCTest • Provided by Xcode • New iOS application projects automatically include a unit testing target • Test classes do not have a header file • It’s not necessary to add application’s source files to the XCTest Target • Each test case is a method with prefix test
  • 44. XCTest • Provided by Xcode • New iOS application projects automatically include a unit testing target • Test classes do not have a header file • It’s not necessary to add application’s source files to the XCTest Target • Each test case is a method with prefix test • Xcode 5 allows to run tests from the editor
  • 45. XCTest Flow Setup Tear DownTest - (void)setUp { [super setUp]; // This method is called before the invocation of each test method in the class. } ! - (void)tearDown { // This method is called after the invocation of each test method in the class. [super tearDown]; } ! - (void)testExample { XCTFail(@"No implementation for "%s"", __PRETTY_FUNCTION__); }
  • 46. Test main actions: • Arrange objects, creating and setting them up as necessary. • Act on an object. • Assert that something is as expected. ! - (void)testMakeConversionWithModeMilesToKilometers { // Arrange sut.value = @(1); // Act [sut makeConversionWithMode:ConverterModeMilesToKm]; // Assert XCTAssertTrue([sut.text isEqualToString:@"1.609344"], @"should convert from miles to kilometers"); }
  • 47. @interface ConverterModelTests : XCTestCase { ConverterModel* sut; } @end ! @implementation ConverterModelTests ! - (void)setUp { [super setUp]; sut = [ConverterModel new]; } ! - (void)tearDown { sut = nil; [super tearDown]; } ! - (void)testMakeConversionWithModeMilesToKilometers { // Arrange sut.value = @(1); // Act [sut makeConversionWithMode:ConverterModeMilesToKm]; // Assert XCTAssertTrue([sut.text isEqualToString:@"1.609344"], @"should convert from miles to kilometers"); } ! @end
  • 48. XCTest Asserts • XCTFail (format…) • XCTAssertNil (a1, format…) • XCTAssertNotNil (a1, format…) • XCTAssert (a1, format…) • XCTAssertTrue (a1, format…) • XCTAssertFalse (a1, format…) • XCTAssertEqualObjects (a1, a2, format…) • XCTAssertEquals (a1, a2, format…) • XCTAssertEqualsWithAccuracy (a1, a2, accuracy, format…) • XCTAssertThrows (expression, format…) • XCTAssertThrowsSpecific (expression, exception, format…) • XCTAssertThrowsSpecificNamed (expression, exception, name, format…) • XCTAssertNoThrow (expression, format…) • XCTAssertNoThrowSpecific (expression, exception, format…) • XCTAssertNoThrowSpecificNamed (expression, exception, name, format…)
  • 49. - (void)viewDidLoad { [super viewDidLoad]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(someAction:) name:kSomeNotification object:nil]; }
  • 50. - (void)viewDidLoad { [super viewDidLoad]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(someAction:) name:kSomeNotification object:nil]; } - (void)testViewDidLoadAddsObserverForSomeNotification { // Arrange // Act // Assert ! }
  • 52. Dependency Injection is a software design pattern that implements passing a service to a client, rather than allowing a client to build or find the service.
  • 53. Constructor Injection the dependencies are provided through a class constructor - (id)initWithNotificationCenter:(NSNotificationCenter *)notificationCenter
  • 54. Setter Injection the client exposes a setter method that the injector uses to inject the dependency @property (nonatomic, weak) NSUserDefaults* userDefaults;
  • 55. Dependency Injection providing an instance variable for dependency
  • 56. - (void)viewDidLoad { [super viewDidLoad]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(someAction:) name:kSomeNotification object:nil]; } Dependency - (void)testViewDidLoadAddsObserverForSomeNotification { // Arrange // Act // Assert ! }
  • 57. - (id)initWithNotificationCenter:(NSNotificationCenter *)notificationCenter { self = [super init]; if(self) { _notificationCenter = notificationCenter; } return self; } ! ! - (void)viewDidLoad { [super viewDidLoad]; [_notificationCenter addObserver:self selector:@selector(someAction:) name:kSomeNotification object:nil]; } Inject Dependency
  • 58. Mocks
  • 59. is a fake object in the system that verifies the object under test interacted as expected with the fake object. Mock Object
  • 60. It is common in unit tests to mock or stub collaborators of the system under test so that the test is independent of the implementation of the collaborators. Mock Object SUT Behavior Verification Setup Exercise Verify Tear Down Behavior (Indirect Outputs) Fake Verify
  • 61. Test Mocks SUT communicates with the mock object, and all communication is recorded in the mock. The test uses the mock to verify that the test passes. SUT Mock Communicate Assert
  • 62. Test Stubs Returns specified result for a message, stubs can’t fail the test. SUT Stub Communicate Assert
  • 63. @interface ConverterViewController : UIViewController ! @property (nonatomic, weak) NSNotificationCenter* notificationCenter; ! @end ! ! @implementation ConverterViewController ! - (void)viewDidLoad { [super viewDidLoad]; [_notificationCenter addObserver:self selector:@selector(someAction:) name:kSomeNotification object:nil]; } ! @end Injected Dependency
  • 64. @interface ConverterViewController : UIViewController ! @property (nonatomic, weak) NSNotificationCenter* notificationCenter; ! @end ! ! @implementation ConverterViewController ! - (void)viewDidLoad { [super viewDidLoad]; [_notificationCenter addObserver:self selector:@selector(someAction:) name:kSomeNotification object:nil]; } ! @end Injected Dependency Replace with a mock
  • 65. What we need? •an object that responds to addObserver:selector:name:object: •possibility to record a call •check for notification’s name •verification
  • 66. @interface FakeNotificationCenter : NSObject { BOOL _hasCalled; } @property (nonatomic, strong) NSString* expectedName; ! - (void)addObserver:(id)observer selector:(SEL)aSelector name:(NSString *)aName object:(id)anObject; - (void)verify; ! @end ! ! @implementation FakeNotificationCenter ! - (void)addObserver:(id)observer selector:(SEL)aSelector name:(NSString *)aName object:(id)anObject { _hasCalled = [_expectedName isEqualToString:aName]; } ! - (void)verify { NSAssert(_hasCalled, @"expected method was not called with specified parameters"); } ! @end What we can do
  • 67. - (void)testViewDidLoadAddsObserverForSomeNotification { // Arrange FakeNotificationCenter* fake = [FakeNotificationCenter new]; fake.expectedName = kSomeNotification; sut.notificationCenter = (id)fake; // Assert [fake verify]; } ! How can we use it?
  • 68. - (void)testViewDidLoadAddsObserverForSomeNotification { // Arrange FakeNotificationCenter* fake = [FakeNotificationCenter new]; fake.expectedName = kSomeNotification; sut.notificationCenter = (id)fake; ! // Assert [fake verify]; } ! -[ConverterViewControllerTests testViewDidLoadAddsObserver] failed: expected method was not called with specified parameters How can we use it?
  • 69. - (void)testViewDidLoadAddsObserverForSomeNotification { // Arrange FakeNotificationCenter* fake = [FakeNotificationCenter new]; fake.expectedName = kSomeNotification; sut.notificationCenter = (id)fake; ! // Act [sut viewDidLoad]; // Assert [fake verify]; } How can we use it?
  • 71. OCMock Provides •stub objects that return pre-determined values for specific method invocations •dynamic mocks that can be used to verify interaction patterns •partial mocks to overwrite selected methods of existing objects
  • 72. Mocks // Creates a mock object that can be used as if it were an instance of // SomeClass. id mock = [OCMockObject mockForClass:[SomeClass class]]; ! ! // Tells the mock object that someMethod: should be called with an argument // that is equal to someArgument. [[mock expect] someMethod:someArgument]; ! // After this setup the functionality under test should be invoked // followed by [mock verify]; ! ! // When a method is called on a mock object that has not been set up with // either expect or stub the mock object will raise an exception. This // fail-fast mode can be turned off by creating a "nice" mock: id mock = [OCMockObject niceMockForClass:[SomeClass class]]; ! // While nice mocks will simply ignore all unexpected methods it is // possible to disallow specific methods: [[mock reject] someMethod];
  • 73. Stubs // Tells the mock object that when someMethod: is called with // someArgument it should return aValue. [[[mock stub] andReturn:aValue] someMethod:someArgument]; ! ! ! // It is not possible to pass primitive types directly. [[[mock stub] andReturnValue:@YES] aMethodReturnABoolean:someArgument]; ! ! // The mock object can also throw an exception or post a notification // when a method is called [[[mock stub] andThrow:anException] someMethod:someArgument]; [[[mock stub] andPost:aNotification] someMethod:someArgument]; ! ! ! // If Objective-C blocks are available a block can be used to handle the // invocation and set up a return value void (^theBlock)(NSInvocation *) = ^(NSInvocation *invocation) { /* code that reads and modifies the invocation object */ }; [[[mock stub] andDo:theBlock] someMethod:[OCMArg any]];
  • 74. @interface ConverterViewController : UIViewController ! @property (nonatomic, weak) NSNotificationCenter* notificationCenter; ! @end ! ! @implementation ConverterViewController ! - (void)viewDidLoad { [super viewDidLoad]; [_notificationCenter addObserver:self selector:@selector(someAction:) name:kSomeNotification object:nil]; } ! @end Injected Dependency
  • 75. - (void)testViewDidLoadAddsObserver { // Arrange id mock = [OCMockObject mockForClass:[NSNotificationCenter class]]; [[mock expect] addObserver:sut selector:[OCMArg anySelector] name:kConverterModelDidUpdateNotification object:OCMOCK_ANY]; sut.notificationCenter = mock; ! // Act [sut viewDidLoad]; // Assert [mock verify]; } How we test this with OCMock
  • 77. How to start with Existing Project • All developers in team must write and run tests
  • 78. How to start with Existing Project • All developers in team must write and run tests • Start with warnings and bugs
  • 79. How to start with Existing Project • All developers in team must write and run tests • Start with warnings and bugs • Isolate modules and classes
  • 80. How to start with Existing Project • All developers in team must write and run tests • Start with warnings and bugs • Isolate modules and classes • Don’t miss refactoring
  • 81. How to start with Existing Project • All developers in team must write and run tests • Start with warnings and bugs • Isolate modules and classes • Don’t miss refactoring • Increase test-coverage step-by-step with new functionality