SlideShare uma empresa Scribd logo
1 de 48
Baixar para ler offline
Unit Testing in iOS
featuring OCUnit, GHUnit & OCMock
            works for OS X too!




               @hpique
The sad fate of developers who don’t write unit tests
Agenda

• Unit testing
• OCUnit
• GHUnit
• OCMock
• Profit!
unit test
             =
code that tests a single unit
          of code
Hey look! A unit test!
- (void) testColorFromPointAndSize_SizeZero
{
    // Prepare input
    CGSize size = CGSizeZero;
    CGPoint point = CGPointZero;

    // Do something
    UIColor *color = [_viewController colorFromPoint:point andSize:size];

    // Validate output
    STAssertNil(color, @"Color must be nil when size is zero");
}
Reasons not to unit
      test
...
ReasonsExcuses not
    to unit test
Excuses

• “I don’t need it”
• “Deadline is too tight”
• “It’s not applicable for this [project|
  class|method]”

• “Unit testing in Xcode sucks”
Reasons to unit test
• Fix bugs early
• Refine design
• Easier to make changes
• Instant gratification :)
• Useful documentation
• Reduce testing time
quality code and testable
  code are best buds
When?

• After writing code
• Before writing code (TDD)
• After fixing a bug
Definitions
          Test Suite

           SetUp

Test Case Test Case Test Case

          TearDown
Agenda

• Unit testing
• OCUnit
• GHUnit
• OCMock
• Profit!
OCUnit


• De-facto unit testing framework for
  Obj-C

• Xcode provides native support
+N
#import <SenTestingKit/SenTestingKit.h>

@interface HelloWorldTests : SenTestCase

@end

@implementation HelloWorldTests

- (void)setUp
{
    [super setUp];

    // Set-up code here.
}

- (void)tearDown
{
    // Tear-down code here.

       [super tearDown];
}

- (void)testExample
{
    STFail(@"Unit tests are not implemented yet in HelloWorldTests");
}

@end
Writing tests with
        OCUnit
• Each Test Suite is a class that inherits
  from SenTestCase

• Each Test Case is a method with prefix
  test

• setUp & tearDown are optional
+U
Console output
2011-12-09 12:43:01.394 HelloWorld[2858:fb03] Applications are expected to have a
root view controller at the end of application launch
Test Suite 'All tests' started at 2011-12-09 11:43:01 +0000
Test Suite '/Users/hermespique/Library/Developer/Xcode/DerivedData/HelloWorld-
ezilismrgmrzecbbsndapbyeczre/Build/Products/Debug-iphonesimulator/
HelloWorldTests.octest(Tests)' started at 2011-12-09 11:43:01 +0000
Test Suite 'HelloWorldTests' started at 2011-12-09 11:43:01 +0000
Test Case '-[HelloWorldTests testExample]' started.
/Users/hermespique/Documents/workspace/HelloWorld/HelloWorldTests/
HelloWorldTests.m:33: error: -[HelloWorldTests testExample] : Unit tests are not
implemented yet in HelloWorldTests
Test Case '-[HelloWorldTests testExample]' failed (0.000 seconds).
Test Suite 'HelloWorldTests' finished at 2011-12-09 11:43:01 +0000.
Executed 1 test, with 1 failure (0 unexpected) in 0.000 (0.000) seconds
Test Suite '/Users/hermespique/Library/Developer/Xcode/DerivedData/HelloWorld-
ezilismrgmrzecbbsndapbyeczre/Build/Products/Debug-iphonesimulator/
HelloWorldTests.octest(Tests)' finished at 2011-12-09 11:43:01 +0000.
Executed 1 test, with 1 failure (0 unexpected) in 0.000 (0.000) seconds
Test Suite 'All tests' finished at 2011-12-09 11:43:01 +0000.
Executed 1 test, with 1 failure (0 unexpected) in 0.000 (0.001) seconds
OCUnit Macros
STAssertEqualObjects(a1, a2, description, ...)
STAssertEquals(a1, a2, description, ...)
STAssertEqualsWithAccuracy(a1, a2, accuracy, description, ...)
STFail(description, ...)
STAssertNil(a1, description, ...)
STAssertNotNil(a1, description, ...)
STAssertTrue(expr, description, ...)
STAssertTrueNoThrow(expr, description, ...)
STAssertFalse(expr, description, ...)
STAssertFalseNoThrow(expr, description, ...)
STAssertThrows(expr, description, ...)
STAssertThrowsSpecific(expr, specificException, description, ...)
STAssertThrowsSpecificNamed(expr, specificException, aName, description, ...)
STAssertNoThrow(expr, description, ...)
STAssertNoThrowSpecific(expr, specificException, description, ...)
STAssertNoThrowSpecificNamed(expr, specificException, aName, description, ...)
Most used macros
STAssertTrue(expr, description, ...)

STAssertFalse(expr, description, ...)

STAssertNil(a1, description, ...)

STAssertNotNil(a1, description, ...)

STAssertEqualObjects(a1, a2, description, ...)

STAssertEquals(a1, a2, description, ...)

STFail(description, ...)

STAssertThrows(expr, description, ...)
Let’s see some code!




github.com/hpique/Unit-Testing-in-iOS-Sample-Code
Agenda

• Unit testing
• OCUnit
• GHUnit
• OCMock
• Profit!
GHUnit
• The other Unit Testing framework for
  Obj-C

• Open-source: github.com/gabriel/gh-
  unit

• GUI!
• No Xcode native support
• Compatible with OCUnit
#import <GHUnitIOS/GHUnit.h>

@interface ExampleTest : GHTestCase
@end

@implementation ExampleTest

- (BOOL)shouldRunOnMainThread {
    return NO;
}

- (void)setUpClass {
    // Run at start of all tests in the class
}

- (void)setUp {
    // Run before each test method
}

- (void)tearDown {
    // Run after each test method
}

- (void)tearDownClass {
    // Run at end of all tests in the class
}

- (void)testFoo {
    NSString *a = @"foo";
    GHAssertNotNil(a, nil);
}

@end
If you’re into macros...
GHAssertNoErr(a1, description, ...)           GHAssertEquals(a1, a2, description, ...)
GHAssertErr(a1, a2, description, ...)         GHAbsoluteDifference(left,right)
GHAssertNotNULL(a1, description, ...)         (MAX(left,right)-MIN(left,right))
GHAssertNULL(a1, description, ...)            GHAssertEqualsWithAccuracy(a1, a2,
GHAssertNotEquals(a1, a2, description, ...)   accuracy, description, ...)
GHAssertNotEqualObjects(a1, a2, desc, ...)    GHFail(description, ...)
GHAssertOperation(a1, a2, op,                 GHAssertNil(a1, description, ...)
description, ...)                             GHAssertNotNil(a1, description, ...)
GHAssertGreaterThan(a1, a2,                   GHAssertTrue(expr, description, ...)
description, ...)                             GHAssertTrueNoThrow(expr,
GHAssertGreaterThanOrEqual(a1, a2,            description, ...)
description, ...)                             GHAssertFalse(expr, description, ...)
GHAssertLessThan(a1, a2, description, ...)    GHAssertFalseNoThrow(expr,
GHAssertLessThanOrEqual(a1, a2,               description, ...)
description, ...)                             GHAssertThrows(expr, description, ...)
GHAssertEqualStrings(a1, a2,                  GHAssertThrowsSpecific(expr,
description, ...)                             specificException, description, ...)
GHAssertNotEqualStrings(a1, a2,               GHAssertThrowsSpecificNamed(expr,
description, ...)                             specificException, aName,
GHAssertEqualCStrings(a1, a2,                 description, ...)
description, ...)                             GHAssertNoThrow(expr, description, ...)
GHAssertNotEqualCStrings(a1, a2,              GHAssertNoThrowSpecific(expr,
description, ...)                             specificException, description, ...)
GHAssertEqualObjects(a1, a2,                  GHAssertNoThrowSpecificNamed(expr,
description, ...)                             specificException, aName,
                                              description, ...)
GHUnitAsyncTestCase
#import <GHUnitIOS/GHUnit.h>

@interface AsyncTest : GHAsyncTestCase { }
@end

@implementation AsyncTest

- (void)testURLConnection {
    [self prepare];

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://
www.google.com"]];
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
delegate:self startImmediately:YES];

       [self waitForStatus:kGHUnitWaitStatusSuccess timeout:10.0];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    [self notify:kGHUnitWaitStatusSuccess forSelector:@selector(testURLConnection)];
}

@end
Configure GHUnit
1. Create target
2. Add GHUnitiOS.framework
 2.1.and QuartzCore.framework!
3. Modify Other Linker Flags
4. Change AppDelegate
1. Create target
1. Create target
2. Add
GHUnitiOS.framework
1. Download from github & unzip
2. > cd gh-unit/Project-iOS
3. > make
                    or
Download the latest stable framework from
github downloads
3. Modify Other Link
        Flags

• Add -all_load
• Add -ObjC
4. Change AppDelegate
   1. Remove default AppDelegate
   2. Modify main.m:

int main(int argc, char *argv[])
{
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil,
@"GHUnitIOSAppDelegate");
    }
}
+B
Let’s see some code!




github.com/hpique/Unit-Testing-in-iOS-Sample-Code
OCUnit vs GHUnit
                     OCUnit           GHUnit

Xcode integration    Built-in         Manual
                     Console        Console
    Results
                    Contextual         GUI
                                   More macros
  Development                      GHAsyncTestCase

                                    Everything,
   Execution        Everything
                                 selection or failed
Using OCUnit tests in
     GHUnit target
  1. Add OCUnit tests to target
  2. Add tested files to target
  3. Add SenTestKit.framework
  4. Add this to Framework Search Paths
     (order matters):
$(SDKROOT)/Developer/Library/Frameworks
$(DEVELOPER_LIBRARY_DIR)/Frameworks
Agenda

• Unit testing
• OCUnit
• GHUnit
• OCMock
• Profit!
mock object
           =
simulated object that
mimics the behavior
  of a real object in
   controlled ways
When to mock an
        object?
• supplies non-deterministic results (ie:
  sensors)

• has states that are difficult to create or
  reproduce (ie: a network error)

• is slow (ie: database)
• does not yet exist or may change behavior
• to avoid writing “test code”
OCMock
• De-facto mocking framework for Obj-C
• Open-source: github.com/erikdoe/
  ocmock

• mock objects on the fly via the
  trampoline pattern

• Complementary with OCUnit & GHUnit
Hey look! Mock objects!
- (void) testHandleGesture
{
    // Prepare input and state
    id viewMock = [OCMockObject partialMockForObject:_viewController.view];
    CGRect viewFrame = CGRectMake(0, 0, 320, 480);
    [[[viewMock stub] andReturnValue:OCMOCK_VALUE(viewFrame)] frame];
    _viewController.view = viewMock;

    UIGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] init];
    id gestureMock = [OCMockObject partialMockForObject:gesture];
    CGPoint gesturePoint = CGPointMake(viewFrame.size.width / 2,
                                       viewFrame.size.height / 2);
    [[[gestureMock stub]
      andReturnValue:OCMOCK_VALUE(gesturePoint)] locationInView:[OCMArg any]];

    // Do something that changes state
    [_viewController handleGesture:gestureMock];

    // Validate state
    UIColor *expectedColor = [UIColor colorWithRed:0.5 green:0.5 blue:0 alpha:1];
    UIColor *color = _viewController.view.backgroundColor;
    [self assertEqualsColor:expectedColor toColor:color];
}
Let’s see some code!




github.com/hpique/Unit-Testing-in-iOS-Sample-Code
Thanks!


 @hpique

Mais conteúdo relacionado

Mais procurados

Code generation for alternative languages
Code generation for alternative languagesCode generation for alternative languages
Code generation for alternative languagesRafael Winterhalter
 
Unit Testing: Special Cases
Unit Testing: Special CasesUnit Testing: Special Cases
Unit Testing: Special CasesCiklum Ukraine
 
Introduction to web programming for java and c# programmers by @drpicox
Introduction to web programming for java and c# programmers by @drpicoxIntroduction to web programming for java and c# programmers by @drpicox
Introduction to web programming for java and c# programmers by @drpicoxDavid Rodenas
 
Android testing
Android testingAndroid testing
Android testingSean Tsai
 
Adventures In JavaScript Testing
Adventures In JavaScript TestingAdventures In JavaScript Testing
Adventures In JavaScript TestingThomas Fuchs
 
Algoritmos sujei
Algoritmos sujeiAlgoritmos sujei
Algoritmos sujeigersonjack
 
Secret unit testing tools no one ever told you about
Secret unit testing tools no one ever told you aboutSecret unit testing tools no one ever told you about
Secret unit testing tools no one ever told you aboutDror Helper
 
ReactJS for Programmers
ReactJS for ProgrammersReactJS for Programmers
ReactJS for ProgrammersDavid Rodenas
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good TestsTomek Kaczanowski
 
Voxxed Days Vilnius 2015 - Having fun with Javassist
Voxxed Days Vilnius 2015 - Having fun with JavassistVoxxed Days Vilnius 2015 - Having fun with Javassist
Voxxed Days Vilnius 2015 - Having fun with JavassistAnton Arhipov
 
Redux for ReactJS Programmers
Redux for ReactJS ProgrammersRedux for ReactJS Programmers
Redux for ReactJS ProgrammersDavid Rodenas
 
Static code analysis: what? how? why?
Static code analysis: what? how? why?Static code analysis: what? how? why?
Static code analysis: what? how? why?Andrey Karpov
 
Python testing using mock and pytest
Python testing using mock and pytestPython testing using mock and pytest
Python testing using mock and pytestSuraj Deshmukh
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good TestsTomek Kaczanowski
 
Club of anonimous developers "Refactoring: Legacy code"
Club of anonimous developers "Refactoring: Legacy code"Club of anonimous developers "Refactoring: Legacy code"
Club of anonimous developers "Refactoring: Legacy code"Victor_Cr
 

Mais procurados (20)

Code generation for alternative languages
Code generation for alternative languagesCode generation for alternative languages
Code generation for alternative languages
 
Unit Testing: Special Cases
Unit Testing: Special CasesUnit Testing: Special Cases
Unit Testing: Special Cases
 
Introduction to web programming for java and c# programmers by @drpicox
Introduction to web programming for java and c# programmers by @drpicoxIntroduction to web programming for java and c# programmers by @drpicox
Introduction to web programming for java and c# programmers by @drpicox
 
Migrating to JUnit 5
Migrating to JUnit 5Migrating to JUnit 5
Migrating to JUnit 5
 
Android testing
Android testingAndroid testing
Android testing
 
Adventures In JavaScript Testing
Adventures In JavaScript TestingAdventures In JavaScript Testing
Adventures In JavaScript Testing
 
Introduzione al TDD
Introduzione al TDDIntroduzione al TDD
Introduzione al TDD
 
Agile Swift
Agile SwiftAgile Swift
Agile Swift
 
Agile Android
Agile AndroidAgile Android
Agile Android
 
Algoritmos sujei
Algoritmos sujeiAlgoritmos sujei
Algoritmos sujei
 
Secret unit testing tools no one ever told you about
Secret unit testing tools no one ever told you aboutSecret unit testing tools no one ever told you about
Secret unit testing tools no one ever told you about
 
ReactJS for Programmers
ReactJS for ProgrammersReactJS for Programmers
ReactJS for Programmers
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
 
Voxxed Days Vilnius 2015 - Having fun with Javassist
Voxxed Days Vilnius 2015 - Having fun with JavassistVoxxed Days Vilnius 2015 - Having fun with Javassist
Voxxed Days Vilnius 2015 - Having fun with Javassist
 
Redux for ReactJS Programmers
Redux for ReactJS ProgrammersRedux for ReactJS Programmers
Redux for ReactJS Programmers
 
Static code analysis: what? how? why?
Static code analysis: what? how? why?Static code analysis: what? how? why?
Static code analysis: what? how? why?
 
Python testing using mock and pytest
Python testing using mock and pytestPython testing using mock and pytest
Python testing using mock and pytest
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
How to fake_properly
How to fake_properlyHow to fake_properly
How to fake_properly
 
Club of anonimous developers "Refactoring: Legacy code"
Club of anonimous developers "Refactoring: Legacy code"Club of anonimous developers "Refactoring: Legacy code"
Club of anonimous developers "Refactoring: Legacy code"
 

Semelhante a Unit testing in iOS featuring OCUnit, GHUnit & OCMock

Grails unit testing
Grails unit testingGrails unit testing
Grails unit testingpleeps
 
멀티플랫폼 앱 개발과 테스팅
멀티플랫폼 앱 개발과 테스팅멀티플랫폼 앱 개발과 테스팅
멀티플랫폼 앱 개발과 테스팅WooKyoung Noh
 
Describe's Full of It's
Describe's Full of It'sDescribe's Full of It's
Describe's Full of It'sJim Lynch
 
In search of JavaScript code quality: unit testing
In search of JavaScript code quality: unit testingIn search of JavaScript code quality: unit testing
In search of JavaScript code quality: unit testingAnna Khabibullina
 
Testing basics for developers
Testing basics for developersTesting basics for developers
Testing basics for developersAnton Udovychenko
 
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdfHans Jones
 
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Paul King
 
Unit testing patterns for concurrent code
Unit testing patterns for concurrent codeUnit testing patterns for concurrent code
Unit testing patterns for concurrent codeDror Helper
 
Javascript tdd byandreapaciolla
Javascript tdd byandreapaciollaJavascript tdd byandreapaciolla
Javascript tdd byandreapaciollaAndrea Paciolla
 
Testing, Performance Analysis, and jQuery 1.4
Testing, Performance Analysis, and jQuery 1.4Testing, Performance Analysis, and jQuery 1.4
Testing, Performance Analysis, and jQuery 1.4jeresig
 
Testing NodeJS with Mocha, Should, Sinon, and JSCoverage
Testing NodeJS with Mocha, Should, Sinon, and JSCoverageTesting NodeJS with Mocha, Should, Sinon, and JSCoverage
Testing NodeJS with Mocha, Should, Sinon, and JSCoveragemlilley
 
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalksSelenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalksLohika_Odessa_TechTalks
 
Unit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and HowsUnit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and Howsatesgoral
 
Developer Test - Things to Know
Developer Test - Things to KnowDeveloper Test - Things to Know
Developer Test - Things to Knowvilniusjug
 

Semelhante a Unit testing in iOS featuring OCUnit, GHUnit & OCMock (20)

Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
 
멀티플랫폼 앱 개발과 테스팅
멀티플랫폼 앱 개발과 테스팅멀티플랫폼 앱 개발과 테스팅
멀티플랫폼 앱 개발과 테스팅
 
Describe's Full of It's
Describe's Full of It'sDescribe's Full of It's
Describe's Full of It's
 
In search of JavaScript code quality: unit testing
In search of JavaScript code quality: unit testingIn search of JavaScript code quality: unit testing
In search of JavaScript code quality: unit testing
 
Junit and testNG
Junit and testNGJunit and testNG
Junit and testNG
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
Testing basics for developers
Testing basics for developersTesting basics for developers
Testing basics for developers
 
Good Practices On Test Automation
Good Practices On Test AutomationGood Practices On Test Automation
Good Practices On Test Automation
 
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdf
 
Full Stack Unit Testing
Full Stack Unit TestingFull Stack Unit Testing
Full Stack Unit Testing
 
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
 
Unit testing patterns for concurrent code
Unit testing patterns for concurrent codeUnit testing patterns for concurrent code
Unit testing patterns for concurrent code
 
Javascript tdd byandreapaciolla
Javascript tdd byandreapaciollaJavascript tdd byandreapaciolla
Javascript tdd byandreapaciolla
 
Golang dot-testing-lite
Golang dot-testing-liteGolang dot-testing-lite
Golang dot-testing-lite
 
Testing, Performance Analysis, and jQuery 1.4
Testing, Performance Analysis, and jQuery 1.4Testing, Performance Analysis, and jQuery 1.4
Testing, Performance Analysis, and jQuery 1.4
 
Testing NodeJS with Mocha, Should, Sinon, and JSCoverage
Testing NodeJS with Mocha, Should, Sinon, and JSCoverageTesting NodeJS with Mocha, Should, Sinon, and JSCoverage
Testing NodeJS with Mocha, Should, Sinon, and JSCoverage
 
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalksSelenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
 
Unit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and HowsUnit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and Hows
 
Developer Test - Things to Know
Developer Test - Things to KnowDeveloper Test - Things to Know
Developer Test - Things to Know
 
Junit_.pptx
Junit_.pptxJunit_.pptx
Junit_.pptx
 

Mais de Robot Media

Android In-app Billing @ Droidcon Murcia
Android In-app Billing @ Droidcon MurciaAndroid In-app Billing @ Droidcon Murcia
Android In-app Billing @ Droidcon MurciaRobot Media
 
Android in-app billing @ Google DevFest Barcelona 2012
Android in-app billing @ Google DevFest Barcelona 2012Android in-app billing @ Google DevFest Barcelona 2012
Android in-app billing @ Google DevFest Barcelona 2012Robot Media
 
Tracking social media campaigns @ editech
Tracking social media campaigns @ editechTracking social media campaigns @ editech
Tracking social media campaigns @ editechRobot Media
 
The Language of Interactive Children's Books @ toc bologna
The Language of Interactive Children's Books @ toc bolognaThe Language of Interactive Children's Books @ toc bologna
The Language of Interactive Children's Books @ toc bolognaRobot Media
 
Android In-App Billing @ Droidcon 2011
Android In-App Billing @ Droidcon 2011Android In-App Billing @ Droidcon 2011
Android In-App Billing @ Droidcon 2011Robot Media
 
Android In-App Billing @ Barcelona GTUG
Android In-App Billing @ Barcelona GTUGAndroid In-App Billing @ Barcelona GTUG
Android In-App Billing @ Barcelona GTUGRobot Media
 
Droid Comic Viewer: El Ecosistema Android
Droid Comic Viewer: El Ecosistema AndroidDroid Comic Viewer: El Ecosistema Android
Droid Comic Viewer: El Ecosistema AndroidRobot Media
 

Mais de Robot Media (7)

Android In-app Billing @ Droidcon Murcia
Android In-app Billing @ Droidcon MurciaAndroid In-app Billing @ Droidcon Murcia
Android In-app Billing @ Droidcon Murcia
 
Android in-app billing @ Google DevFest Barcelona 2012
Android in-app billing @ Google DevFest Barcelona 2012Android in-app billing @ Google DevFest Barcelona 2012
Android in-app billing @ Google DevFest Barcelona 2012
 
Tracking social media campaigns @ editech
Tracking social media campaigns @ editechTracking social media campaigns @ editech
Tracking social media campaigns @ editech
 
The Language of Interactive Children's Books @ toc bologna
The Language of Interactive Children's Books @ toc bolognaThe Language of Interactive Children's Books @ toc bologna
The Language of Interactive Children's Books @ toc bologna
 
Android In-App Billing @ Droidcon 2011
Android In-App Billing @ Droidcon 2011Android In-App Billing @ Droidcon 2011
Android In-App Billing @ Droidcon 2011
 
Android In-App Billing @ Barcelona GTUG
Android In-App Billing @ Barcelona GTUGAndroid In-App Billing @ Barcelona GTUG
Android In-App Billing @ Barcelona GTUG
 
Droid Comic Viewer: El Ecosistema Android
Droid Comic Viewer: El Ecosistema AndroidDroid Comic Viewer: El Ecosistema Android
Droid Comic Viewer: El Ecosistema Android
 

Último

Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdfChristopherTHyatt
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 

Último (20)

Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 

Unit testing in iOS featuring OCUnit, GHUnit & OCMock

  • 1. Unit Testing in iOS featuring OCUnit, GHUnit & OCMock works for OS X too! @hpique
  • 2. The sad fate of developers who don’t write unit tests
  • 3. Agenda • Unit testing • OCUnit • GHUnit • OCMock • Profit!
  • 4. unit test = code that tests a single unit of code
  • 5. Hey look! A unit test! - (void) testColorFromPointAndSize_SizeZero { // Prepare input CGSize size = CGSizeZero; CGPoint point = CGPointZero; // Do something UIColor *color = [_viewController colorFromPoint:point andSize:size]; // Validate output STAssertNil(color, @"Color must be nil when size is zero"); }
  • 6. Reasons not to unit test
  • 7. ...
  • 8. ReasonsExcuses not to unit test
  • 9. Excuses • “I don’t need it” • “Deadline is too tight” • “It’s not applicable for this [project| class|method]” • “Unit testing in Xcode sucks”
  • 10. Reasons to unit test • Fix bugs early • Refine design • Easier to make changes • Instant gratification :) • Useful documentation • Reduce testing time
  • 11. quality code and testable code are best buds
  • 12. When? • After writing code • Before writing code (TDD) • After fixing a bug
  • 13. Definitions Test Suite SetUp Test Case Test Case Test Case TearDown
  • 14. Agenda • Unit testing • OCUnit • GHUnit • OCMock • Profit!
  • 15. OCUnit • De-facto unit testing framework for Obj-C • Xcode provides native support
  • 16.
  • 17.
  • 18. +N
  • 19. #import <SenTestingKit/SenTestingKit.h> @interface HelloWorldTests : SenTestCase @end @implementation HelloWorldTests - (void)setUp { [super setUp]; // Set-up code here. } - (void)tearDown { // Tear-down code here. [super tearDown]; } - (void)testExample { STFail(@"Unit tests are not implemented yet in HelloWorldTests"); } @end
  • 20. Writing tests with OCUnit • Each Test Suite is a class that inherits from SenTestCase • Each Test Case is a method with prefix test • setUp & tearDown are optional
  • 21. +U
  • 22. Console output 2011-12-09 12:43:01.394 HelloWorld[2858:fb03] Applications are expected to have a root view controller at the end of application launch Test Suite 'All tests' started at 2011-12-09 11:43:01 +0000 Test Suite '/Users/hermespique/Library/Developer/Xcode/DerivedData/HelloWorld- ezilismrgmrzecbbsndapbyeczre/Build/Products/Debug-iphonesimulator/ HelloWorldTests.octest(Tests)' started at 2011-12-09 11:43:01 +0000 Test Suite 'HelloWorldTests' started at 2011-12-09 11:43:01 +0000 Test Case '-[HelloWorldTests testExample]' started. /Users/hermespique/Documents/workspace/HelloWorld/HelloWorldTests/ HelloWorldTests.m:33: error: -[HelloWorldTests testExample] : Unit tests are not implemented yet in HelloWorldTests Test Case '-[HelloWorldTests testExample]' failed (0.000 seconds). Test Suite 'HelloWorldTests' finished at 2011-12-09 11:43:01 +0000. Executed 1 test, with 1 failure (0 unexpected) in 0.000 (0.000) seconds Test Suite '/Users/hermespique/Library/Developer/Xcode/DerivedData/HelloWorld- ezilismrgmrzecbbsndapbyeczre/Build/Products/Debug-iphonesimulator/ HelloWorldTests.octest(Tests)' finished at 2011-12-09 11:43:01 +0000. Executed 1 test, with 1 failure (0 unexpected) in 0.000 (0.000) seconds Test Suite 'All tests' finished at 2011-12-09 11:43:01 +0000. Executed 1 test, with 1 failure (0 unexpected) in 0.000 (0.001) seconds
  • 23. OCUnit Macros STAssertEqualObjects(a1, a2, description, ...) STAssertEquals(a1, a2, description, ...) STAssertEqualsWithAccuracy(a1, a2, accuracy, description, ...) STFail(description, ...) STAssertNil(a1, description, ...) STAssertNotNil(a1, description, ...) STAssertTrue(expr, description, ...) STAssertTrueNoThrow(expr, description, ...) STAssertFalse(expr, description, ...) STAssertFalseNoThrow(expr, description, ...) STAssertThrows(expr, description, ...) STAssertThrowsSpecific(expr, specificException, description, ...) STAssertThrowsSpecificNamed(expr, specificException, aName, description, ...) STAssertNoThrow(expr, description, ...) STAssertNoThrowSpecific(expr, specificException, description, ...) STAssertNoThrowSpecificNamed(expr, specificException, aName, description, ...)
  • 24. Most used macros STAssertTrue(expr, description, ...) STAssertFalse(expr, description, ...) STAssertNil(a1, description, ...) STAssertNotNil(a1, description, ...) STAssertEqualObjects(a1, a2, description, ...) STAssertEquals(a1, a2, description, ...) STFail(description, ...) STAssertThrows(expr, description, ...)
  • 25. Let’s see some code! github.com/hpique/Unit-Testing-in-iOS-Sample-Code
  • 26. Agenda • Unit testing • OCUnit • GHUnit • OCMock • Profit!
  • 27. GHUnit • The other Unit Testing framework for Obj-C • Open-source: github.com/gabriel/gh- unit • GUI! • No Xcode native support • Compatible with OCUnit
  • 28.
  • 29. #import <GHUnitIOS/GHUnit.h> @interface ExampleTest : GHTestCase @end @implementation ExampleTest - (BOOL)shouldRunOnMainThread { return NO; } - (void)setUpClass { // Run at start of all tests in the class } - (void)setUp { // Run before each test method } - (void)tearDown { // Run after each test method } - (void)tearDownClass { // Run at end of all tests in the class } - (void)testFoo { NSString *a = @"foo"; GHAssertNotNil(a, nil); } @end
  • 30. If you’re into macros... GHAssertNoErr(a1, description, ...) GHAssertEquals(a1, a2, description, ...) GHAssertErr(a1, a2, description, ...) GHAbsoluteDifference(left,right) GHAssertNotNULL(a1, description, ...) (MAX(left,right)-MIN(left,right)) GHAssertNULL(a1, description, ...) GHAssertEqualsWithAccuracy(a1, a2, GHAssertNotEquals(a1, a2, description, ...) accuracy, description, ...) GHAssertNotEqualObjects(a1, a2, desc, ...) GHFail(description, ...) GHAssertOperation(a1, a2, op, GHAssertNil(a1, description, ...) description, ...) GHAssertNotNil(a1, description, ...) GHAssertGreaterThan(a1, a2, GHAssertTrue(expr, description, ...) description, ...) GHAssertTrueNoThrow(expr, GHAssertGreaterThanOrEqual(a1, a2, description, ...) description, ...) GHAssertFalse(expr, description, ...) GHAssertLessThan(a1, a2, description, ...) GHAssertFalseNoThrow(expr, GHAssertLessThanOrEqual(a1, a2, description, ...) description, ...) GHAssertThrows(expr, description, ...) GHAssertEqualStrings(a1, a2, GHAssertThrowsSpecific(expr, description, ...) specificException, description, ...) GHAssertNotEqualStrings(a1, a2, GHAssertThrowsSpecificNamed(expr, description, ...) specificException, aName, GHAssertEqualCStrings(a1, a2, description, ...) description, ...) GHAssertNoThrow(expr, description, ...) GHAssertNotEqualCStrings(a1, a2, GHAssertNoThrowSpecific(expr, description, ...) specificException, description, ...) GHAssertEqualObjects(a1, a2, GHAssertNoThrowSpecificNamed(expr, description, ...) specificException, aName, description, ...)
  • 31. GHUnitAsyncTestCase #import <GHUnitIOS/GHUnit.h> @interface AsyncTest : GHAsyncTestCase { } @end @implementation AsyncTest - (void)testURLConnection { [self prepare]; NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http:// www.google.com"]]; NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES]; [self waitForStatus:kGHUnitWaitStatusSuccess timeout:10.0]; } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { [self notify:kGHUnitWaitStatusSuccess forSelector:@selector(testURLConnection)]; } @end
  • 32. Configure GHUnit 1. Create target 2. Add GHUnitiOS.framework 2.1.and QuartzCore.framework! 3. Modify Other Linker Flags 4. Change AppDelegate
  • 35. 2. Add GHUnitiOS.framework 1. Download from github & unzip 2. > cd gh-unit/Project-iOS 3. > make or Download the latest stable framework from github downloads
  • 36. 3. Modify Other Link Flags • Add -all_load • Add -ObjC
  • 37. 4. Change AppDelegate 1. Remove default AppDelegate 2. Modify main.m: int main(int argc, char *argv[]) { @autoreleasepool { return UIApplicationMain(argc, argv, nil, @"GHUnitIOSAppDelegate"); } }
  • 38. +B
  • 39. Let’s see some code! github.com/hpique/Unit-Testing-in-iOS-Sample-Code
  • 40. OCUnit vs GHUnit OCUnit GHUnit Xcode integration Built-in Manual Console Console Results Contextual GUI More macros Development GHAsyncTestCase Everything, Execution Everything selection or failed
  • 41. Using OCUnit tests in GHUnit target 1. Add OCUnit tests to target 2. Add tested files to target 3. Add SenTestKit.framework 4. Add this to Framework Search Paths (order matters): $(SDKROOT)/Developer/Library/Frameworks $(DEVELOPER_LIBRARY_DIR)/Frameworks
  • 42. Agenda • Unit testing • OCUnit • GHUnit • OCMock • Profit!
  • 43. mock object = simulated object that mimics the behavior of a real object in controlled ways
  • 44. When to mock an object? • supplies non-deterministic results (ie: sensors) • has states that are difficult to create or reproduce (ie: a network error) • is slow (ie: database) • does not yet exist or may change behavior • to avoid writing “test code”
  • 45. OCMock • De-facto mocking framework for Obj-C • Open-source: github.com/erikdoe/ ocmock • mock objects on the fly via the trampoline pattern • Complementary with OCUnit & GHUnit
  • 46. Hey look! Mock objects! - (void) testHandleGesture { // Prepare input and state id viewMock = [OCMockObject partialMockForObject:_viewController.view]; CGRect viewFrame = CGRectMake(0, 0, 320, 480); [[[viewMock stub] andReturnValue:OCMOCK_VALUE(viewFrame)] frame]; _viewController.view = viewMock; UIGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] init]; id gestureMock = [OCMockObject partialMockForObject:gesture]; CGPoint gesturePoint = CGPointMake(viewFrame.size.width / 2, viewFrame.size.height / 2); [[[gestureMock stub] andReturnValue:OCMOCK_VALUE(gesturePoint)] locationInView:[OCMArg any]]; // Do something that changes state [_viewController handleGesture:gestureMock]; // Validate state UIColor *expectedColor = [UIColor colorWithRed:0.5 green:0.5 blue:0 alpha:1]; UIColor *color = _viewController.view.backgroundColor; [self assertEqualsColor:expectedColor toColor:color]; }
  • 47. Let’s see some code! github.com/hpique/Unit-Testing-in-iOS-Sample-Code