SlideShare a Scribd company logo
Unit Testing en iOS
       @hpique
Así terminan los programadores que no hacen unit testing
Agenda

• Unit Testing
• OCUnit
• GHUnit
• Profit!
Unit Testing

Testeo de unidades mínimas de
   código mediante código
- (void)testColorFromHex {
    NSString* colorString = @"#d34f01";

    UIColor* color = [colorString colorFromHex];

    const CGFloat *c = CGColorGetComponents(color.CGColor);
    STAssertEquals(c[0], 211/255.0f, colorString, @"");
    STAssertEquals(c[1], 79/255.0f, colorString, @"");
    STAssertEquals(c[2], 1/255.0f, colorString, @"");
    STAssertEquals(CGColorGetAlpha(color.CGColor), 1.0f,
colorString, @"");
}
Razones para no hacer
     unit testing
...
RazonesExcusas para
no hacer unit testing
Excusas
Excusas

• “No lo necesito”
Excusas

• “No lo necesito”
• “El plazo es muy ajustado”
Excusas

• “No lo necesito”
• “El plazo es muy ajustado”
• “No aplica para este proyecto”
Excusas

• “No lo necesito”
• “El plazo es muy ajustado”
• “No aplica para este proyecto”
• “Unit testing en XCode apesta”
Razones para sí hacer
    unit testing
Razones para sí hacer
    unit testing
• Corregir bugs antes
Razones para sí hacer
    unit testing
• Corregir bugs antes
• Refinar el diseño
Razones para sí hacer
    unit testing
• Corregir bugs antes
• Refinar el diseño
• Facilitar cambios
Razones para sí hacer
    unit testing
• Corregir bugs antes
• Refinar el diseño
• Facilitar cambios
• Documentación útil
Razones para sí hacer
    unit testing
• Corregir bugs antes
• Refinar el diseño
• Facilitar cambios
• Documentación útil
• Reducir tiempo de testeo
¿Cuándo?
¿Cuándo?

• Lo antes posible (TDD)
¿Cuándo?

• Lo antes posible (TDD)
• En paralelo
¿Cuándo?

• Lo antes posible (TDD)
• En paralelo
• Al corregir bugs
Definiciones
            Test Suite

             SetUp

Test Case   Test Case    Test Case

            TearDown
Agenda

• Unit Testing
• OCUnit
• GHUnit
• Profit!
OCUnit


• Framework de Unit Testing para Obj-C
• Único framework de testeo integrado
  nativamente en XCode
Unit testing en iOS @ MobileCon Galicia
Unit testing en iOS @ MobileCon Galicia
+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
Escribiendo unit tests
     con OCUnit
• Cada Test Suite es una clase que hereda de
  SenTestCase

• Cada Test Case debe ser un método con el
  prefijo test

• setUp y tearDown son opcionales
+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, ...)
OCUnit 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, ...)
Agenda

• Unit Testing
• OCUnit
• GHUnit
• Profit!
GHUnit

• Framework de Unit Testing para Obj-C
• Open-source: github.com/gabriel/gh-unit
• GUI!
• Compatible con OCUnit
Unit testing en iOS @ MobileCon Galicia
#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
GHUnit 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
Configurar GHUnit

1. Crear target
2. Agregar GHUnitiOS.framework
3. Modificar Other Linker Flags
4. Cambiar de AppDelegate
1. Crear target
1. Crear target
2. Agregar
GHUnitiOS.framework
• Primero debemos hacer build del framework
1. Descargar de github y descomprimir
2. > cd gh-unit/Project-iOS
3. > make
3. Modificar Other Link
         Flags

• Agregar -all_load
• Agregar -objC
4. Cambiar de
          AppDelegate
int main(int argc, char *argv[])
{
    @autoreleasepool {
        return UIApplicationMain(argc,
argv, nil, @"GHUnitIOSAppDelegate");
    }
}
+B
OCUnit vs GHUnit
                    OCUnit           GHUnit
Integración con
                    Built-in          Manual
    XCode
                  Contextual /
  Resultados                      Consola / GUI
                   Consola
                                   Más macros
Programación
                                 GHAsyncTestCase
                                 Todo, selección o
  Ejecución          Todo
                                     fallidos
¡Gracias!


  @hpique

More Related Content

What's hot (20)

PPTX
Test-driven JavaScript Development - OPITZ CONSULTING - Tobias Bosch - Stefa...
OPITZ CONSULTING Deutschland
 
RTF
Easy Button
Adam Dale
 
PDF
Voxxed Days Vilnius 2015 - Having fun with Javassist
Anton Arhipov
 
PDF
Clean code via dependency injection + guice
Jordi Gerona
 
PDF
JavaOne 2015 - Having fun with Javassist
Anton Arhipov
 
PPTX
Migrating to JUnit 5
Rafael Winterhalter
 
PDF
0003 es5 핵심 정리
욱래 김
 
PPTX
Дмитрий Демчук. Кроссплатформенный краш-репорт
Sergey Platonov
 
PDF
Test driven node.js
Jay Harris
 
PDF
Adventures In JavaScript Testing
Thomas Fuchs
 
PDF
Testing, Performance Analysis, and jQuery 1.4
jeresig
 
PDF
Easy Going Groovy 2nd season on DevLOVE
Uehara Junji
 
PPT
Introduzione al TDD
Andrea Francia
 
PDF
Live Updating Swift Code
Bartosz Polaczyk
 
PDF
JEEConf 2017 - Having fun with Javassist
Anton Arhipov
 
KEY
Groovy 1.8の新機能について
Uehara Junji
 
TXT
Maze
yito24
 
PDF
#JavaFX.forReal() - ElsassJUG
Thierry Wasylczenko
 
PDF
Коварный code type ITGM #9
Andrey Zakharevich
 
PDF
Construire une application JavaFX 8 avec gradle
Thierry Wasylczenko
 
Test-driven JavaScript Development - OPITZ CONSULTING - Tobias Bosch - Stefa...
OPITZ CONSULTING Deutschland
 
Easy Button
Adam Dale
 
Voxxed Days Vilnius 2015 - Having fun with Javassist
Anton Arhipov
 
Clean code via dependency injection + guice
Jordi Gerona
 
JavaOne 2015 - Having fun with Javassist
Anton Arhipov
 
Migrating to JUnit 5
Rafael Winterhalter
 
0003 es5 핵심 정리
욱래 김
 
Дмитрий Демчук. Кроссплатформенный краш-репорт
Sergey Platonov
 
Test driven node.js
Jay Harris
 
Adventures In JavaScript Testing
Thomas Fuchs
 
Testing, Performance Analysis, and jQuery 1.4
jeresig
 
Easy Going Groovy 2nd season on DevLOVE
Uehara Junji
 
Introduzione al TDD
Andrea Francia
 
Live Updating Swift Code
Bartosz Polaczyk
 
JEEConf 2017 - Having fun with Javassist
Anton Arhipov
 
Groovy 1.8の新機能について
Uehara Junji
 
Maze
yito24
 
#JavaFX.forReal() - ElsassJUG
Thierry Wasylczenko
 
Коварный code type ITGM #9
Andrey Zakharevich
 
Construire une application JavaFX 8 avec gradle
Thierry Wasylczenko
 

Similar to Unit testing en iOS @ MobileCon Galicia (20)

PPTX
In search of JavaScript code quality: unit testing
Anna Khabibullina
 
PDF
Nativescript angular
Christoffer Noring
 
PDF
Golang dot-testing-lite
Richárd Kovács
 
PPT
2012 JDays Bad Tests Good Tests
Tomek Kaczanowski
 
PDF
33rd Degree 2013, Bad Tests, Good Tests
Tomek Kaczanowski
 
PDF
Describe's Full of It's
Jim Lynch
 
PDF
Tdd iPhone For Dummies
Giordano Scalzo
 
PPTX
Introduction to nsubstitute
Suresh Loganatha
 
PPT
Groovy Introduction - JAX Germany - 2008
Guillaume Laforge
 
PDF
Understanding JavaScript Testing
jeresig
 
PPTX
Testing with VS2010 - A Bugs Life
Peter Gfader
 
PDF
Php unit the-mostunknownparts
Bastian Feder
 
PDF
Scala test
Inphina Technologies
 
PDF
Scala test
Meetu Maltiar
 
PPTX
We Love Performance! How Tic Toc Games Uses ECS in Mobile Puzzle Games
Unity Technologies
 
ZIP
Automated Frontend Testing
Neil Crosby
 
KEY
Agile Iphone Development
Giordano Scalzo
 
PDF
TypeScript for Java Developers
Yakov Fain
 
PDF
Clean coding-practices
John Ferguson Smart Limited
 
PDF
JavaScript Editions ES7, ES8 and ES9 vs V8
Rafael Casuso Romate
 
In search of JavaScript code quality: unit testing
Anna Khabibullina
 
Nativescript angular
Christoffer Noring
 
Golang dot-testing-lite
Richárd Kovács
 
2012 JDays Bad Tests Good Tests
Tomek Kaczanowski
 
33rd Degree 2013, Bad Tests, Good Tests
Tomek Kaczanowski
 
Describe's Full of It's
Jim Lynch
 
Tdd iPhone For Dummies
Giordano Scalzo
 
Introduction to nsubstitute
Suresh Loganatha
 
Groovy Introduction - JAX Germany - 2008
Guillaume Laforge
 
Understanding JavaScript Testing
jeresig
 
Testing with VS2010 - A Bugs Life
Peter Gfader
 
Php unit the-mostunknownparts
Bastian Feder
 
Scala test
Meetu Maltiar
 
We Love Performance! How Tic Toc Games Uses ECS in Mobile Puzzle Games
Unity Technologies
 
Automated Frontend Testing
Neil Crosby
 
Agile Iphone Development
Giordano Scalzo
 
TypeScript for Java Developers
Yakov Fain
 
Clean coding-practices
John Ferguson Smart Limited
 
JavaScript Editions ES7, ES8 and ES9 vs V8
Rafael Casuso Romate
 
Ad

More from Robot Media (7)

PDF
Android In-app Billing @ Droidcon Murcia
Robot Media
 
KEY
Android in-app billing @ Google DevFest Barcelona 2012
Robot Media
 
KEY
Tracking social media campaigns @ editech
Robot Media
 
KEY
The Language of Interactive Children's Books @ toc bologna
Robot Media
 
KEY
Android In-App Billing @ Droidcon 2011
Robot Media
 
KEY
Android In-App Billing @ Barcelona GTUG
Robot Media
 
PPT
Droid Comic Viewer: El Ecosistema Android
Robot Media
 
Android In-app Billing @ Droidcon Murcia
Robot Media
 
Android in-app billing @ Google DevFest Barcelona 2012
Robot Media
 
Tracking social media campaigns @ editech
Robot Media
 
The Language of Interactive Children's Books @ toc bologna
Robot Media
 
Android In-App Billing @ Droidcon 2011
Robot Media
 
Android In-App Billing @ Barcelona GTUG
Robot Media
 
Droid Comic Viewer: El Ecosistema Android
Robot Media
 
Ad

Recently uploaded (20)

PDF
Market Insight : ETH Dominance Returns
CIFDAQ
 
PDF
OpenInfra ID 2025 - Are Containers Dying? Rethinking Isolation with MicroVMs.pdf
Muhammad Yuga Nugraha
 
PPTX
AVL ( audio, visuals or led ), technology.
Rajeshwri Panchal
 
PDF
Lecture A - AI Workflows for Banking.pdf
Dr. LAM Yat-fai (林日辉)
 
PDF
The Past, Present & Future of Kenya's Digital Transformation
Moses Kemibaro
 
PPTX
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
PPTX
Agentic AI in Healthcare Driving the Next Wave of Digital Transformation
danielle hunter
 
PDF
Alpha Altcoin Setup : TIA - 19th July 2025
CIFDAQ
 
PDF
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
PDF
Peak of Data & AI Encore - Real-Time Insights & Scalable Editing with ArcGIS
Safe Software
 
PDF
Responsible AI and AI Ethics - By Sylvester Ebhonu
Sylvester Ebhonu
 
PPTX
python advanced data structure dictionary with examples python advanced data ...
sprasanna11
 
PDF
How ETL Control Logic Keeps Your Pipelines Safe and Reliable.pdf
Stryv Solutions Pvt. Ltd.
 
PDF
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
PDF
NewMind AI Weekly Chronicles – July’25, Week III
NewMind AI
 
PPTX
Agile Chennai 18-19 July 2025 | Emerging patterns in Agentic AI by Bharani Su...
AgileNetwork
 
PDF
Generative AI vs Predictive AI-The Ultimate Comparison Guide
Lily Clark
 
PDF
Researching The Best Chat SDK Providers in 2025
Ray Fields
 
PDF
Build with AI and GDG Cloud Bydgoszcz- ADK .pdf
jaroslawgajewski1
 
PDF
Integrating IIoT with SCADA in Oil & Gas A Technical Perspective.pdf
Rejig Digital
 
Market Insight : ETH Dominance Returns
CIFDAQ
 
OpenInfra ID 2025 - Are Containers Dying? Rethinking Isolation with MicroVMs.pdf
Muhammad Yuga Nugraha
 
AVL ( audio, visuals or led ), technology.
Rajeshwri Panchal
 
Lecture A - AI Workflows for Banking.pdf
Dr. LAM Yat-fai (林日辉)
 
The Past, Present & Future of Kenya's Digital Transformation
Moses Kemibaro
 
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
Agentic AI in Healthcare Driving the Next Wave of Digital Transformation
danielle hunter
 
Alpha Altcoin Setup : TIA - 19th July 2025
CIFDAQ
 
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
Peak of Data & AI Encore - Real-Time Insights & Scalable Editing with ArcGIS
Safe Software
 
Responsible AI and AI Ethics - By Sylvester Ebhonu
Sylvester Ebhonu
 
python advanced data structure dictionary with examples python advanced data ...
sprasanna11
 
How ETL Control Logic Keeps Your Pipelines Safe and Reliable.pdf
Stryv Solutions Pvt. Ltd.
 
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
NewMind AI Weekly Chronicles – July’25, Week III
NewMind AI
 
Agile Chennai 18-19 July 2025 | Emerging patterns in Agentic AI by Bharani Su...
AgileNetwork
 
Generative AI vs Predictive AI-The Ultimate Comparison Guide
Lily Clark
 
Researching The Best Chat SDK Providers in 2025
Ray Fields
 
Build with AI and GDG Cloud Bydgoszcz- ADK .pdf
jaroslawgajewski1
 
Integrating IIoT with SCADA in Oil & Gas A Technical Perspective.pdf
Rejig Digital
 

Unit testing en iOS @ MobileCon Galicia

  • 1. Unit Testing en iOS @hpique
  • 2. Así terminan los programadores que no hacen unit testing
  • 3. Agenda • Unit Testing • OCUnit • GHUnit • Profit!
  • 4. Unit Testing Testeo de unidades mínimas de código mediante código
  • 5. - (void)testColorFromHex { NSString* colorString = @"#d34f01"; UIColor* color = [colorString colorFromHex]; const CGFloat *c = CGColorGetComponents(color.CGColor); STAssertEquals(c[0], 211/255.0f, colorString, @""); STAssertEquals(c[1], 79/255.0f, colorString, @""); STAssertEquals(c[2], 1/255.0f, colorString, @""); STAssertEquals(CGColorGetAlpha(color.CGColor), 1.0f, colorString, @""); }
  • 6. Razones para no hacer unit testing
  • 7. ...
  • 10. Excusas • “No lo necesito”
  • 11. Excusas • “No lo necesito” • “El plazo es muy ajustado”
  • 12. Excusas • “No lo necesito” • “El plazo es muy ajustado” • “No aplica para este proyecto”
  • 13. Excusas • “No lo necesito” • “El plazo es muy ajustado” • “No aplica para este proyecto” • “Unit testing en XCode apesta”
  • 14. Razones para sí hacer unit testing
  • 15. Razones para sí hacer unit testing • Corregir bugs antes
  • 16. Razones para sí hacer unit testing • Corregir bugs antes • Refinar el diseño
  • 17. Razones para sí hacer unit testing • Corregir bugs antes • Refinar el diseño • Facilitar cambios
  • 18. Razones para sí hacer unit testing • Corregir bugs antes • Refinar el diseño • Facilitar cambios • Documentación útil
  • 19. Razones para sí hacer unit testing • Corregir bugs antes • Refinar el diseño • Facilitar cambios • Documentación útil • Reducir tiempo de testeo
  • 21. ¿Cuándo? • Lo antes posible (TDD)
  • 22. ¿Cuándo? • Lo antes posible (TDD) • En paralelo
  • 23. ¿Cuándo? • Lo antes posible (TDD) • En paralelo • Al corregir bugs
  • 24. Definiciones Test Suite SetUp Test Case Test Case Test Case TearDown
  • 25. Agenda • Unit Testing • OCUnit • GHUnit • Profit!
  • 26. OCUnit • Framework de Unit Testing para Obj-C • Único framework de testeo integrado nativamente en XCode
  • 29. +N
  • 30. #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
  • 31. Escribiendo unit tests con OCUnit • Cada Test Suite es una clase que hereda de SenTestCase • Cada Test Case debe ser un método con el prefijo test • setUp y tearDown son opcionales
  • 32. +U
  • 33. 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
  • 34. 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, ...)
  • 35. OCUnit 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, ...)
  • 36. Agenda • Unit Testing • OCUnit • GHUnit • Profit!
  • 37. GHUnit • Framework de Unit Testing para Obj-C • Open-source: github.com/gabriel/gh-unit • GUI! • Compatible con OCUnit
  • 39. #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
  • 40. GHUnit 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, ...)
  • 41. 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
  • 42. Configurar GHUnit 1. Crear target 2. Agregar GHUnitiOS.framework 3. Modificar Other Linker Flags 4. Cambiar de AppDelegate
  • 45. 2. Agregar GHUnitiOS.framework • Primero debemos hacer build del framework 1. Descargar de github y descomprimir 2. > cd gh-unit/Project-iOS 3. > make
  • 46. 3. Modificar Other Link Flags • Agregar -all_load • Agregar -objC
  • 47. 4. Cambiar de AppDelegate int main(int argc, char *argv[]) { @autoreleasepool { return UIApplicationMain(argc, argv, nil, @"GHUnitIOSAppDelegate"); } }
  • 48. +B
  • 49. OCUnit vs GHUnit OCUnit GHUnit Integración con Built-in Manual XCode Contextual / Resultados Consola / GUI Consola Más macros Programación GHAsyncTestCase Todo, selección o Ejecución Todo fallidos

Editor's Notes