Slide 1

Slide 1 text

Unit Testing for iOS $> git clone --recursive https://github.com/moredip/run2bart-iOS.git $> cd run2bart-iOS $> open Run2Bart/Run2Bart.xcworkspace you should have already done this:

Slide 2

Slide 2 text

me me me Pete Hodgson Consultant at ThoughtWorks @ph1 blog.thepete.net

Slide 3

Slide 3 text

tell me about yourself experience with iOS? experience with automated testing? experience testing with iOS?

Slide 4

Slide 4 text

goals for the workshop hands on experience good testing practices overview of all the major moving parts of Kiwi introduction to the advanced stuff

Slide 5

Slide 5 text

some theory, some hands-on (with pairing!) workshop format

Slide 6

Slide 6 text

interrupt, raise your hand, ask questions Please

Slide 7

Slide 7 text

why should you care? Unit Testing

Slide 8

Slide 8 text

No content

Slide 9

Slide 9 text

No content

Slide 10

Slide 10 text

No content

Slide 11

Slide 11 text

1. write code 2. submit stack of cards 3. wait (probably overnight) 4. find out if your program worked

Slide 12

Slide 12 text

Feedback

Slide 13

Slide 13 text

write it check it

Slide 14

Slide 14 text

feedback

Slide 15

Slide 15 text

24 hrs punchcards

Slide 16

Slide 16 text

60 mins big ol’ C++ program

Slide 17

Slide 17 text

http://xkcd.com/303/

Slide 18

Slide 18 text

10 secs an iOS app

Slide 19

Slide 19 text

what’s next?

Slide 20

Slide 20 text

of feedback speed

Slide 21

Slide 21 text

of feedback quality

Slide 22

Slide 22 text

syntax vs. semantics

Slide 23

Slide 23 text

does it compile? static analysis unit testing

Slide 24

Slide 24 text

unit testing means better feedback

Slide 25

Slide 25 text

what is a unit test?

Slide 26

Slide 26 text

what is NOT unit test?

Slide 27

Slide 27 text

types of automated testing

Slide 28

Slide 28 text

Your App End User Backend Services

Slide 29

Slide 29 text

Unit Test Your App End User Backend Services

Slide 30

Slide 30 text

Integration Test Your App End User Backend Services

Slide 31

Slide 31 text

Acceptance Test Your App End User Backend Services

Slide 32

Slide 32 text

Acceptance Test Your App End User Backend Services The App

Slide 33

Slide 33 text

Acceptance Unit Integration

Slide 34

Slide 34 text

“my first unit test” with kiwi

Slide 35

Slide 35 text

what is kiwi? open-source tool builds on top of stock XCode tooling adds nicer ways of organizing tests adds nicer ways to make assertions adds ability to mock/stub

Slide 36

Slide 36 text

setting up a project to use Kiwi

Slide 37

Slide 37 text

Guide: Up and Running with Kiwi https://github.com/allending/Kiwi/wiki

Slide 38

Slide 38 text

CocoaPods makes this a lot easier https://github.com/CocoaPods/CocoaPods

Slide 39

Slide 39 text

what is a unit test?

Slide 40

Slide 40 text

x+1 12 13

Slide 41

Slide 41 text

system under test in out

Slide 42

Slide 42 text

#import "Kiwi.h" SPEC_BEGIN(MyFirstSpec) describe(@"Basic Arithmetic", ^{ it(@"can increment 12",^{ [[theValue(12+1) should] equal:theValue(13)]; }); }); SPEC_END myFirstSpec.m

Slide 43

Slide 43 text

Hands-on: writing our first test

Slide 44

Slide 44 text

$> git checkout sl-2 $> git clean -dxf 1: Close XCode 2: 3: Open Run2Bart.xcworkspace

Slide 45

Slide 45 text

#import "Kiwi.h" SPEC_BEGIN(MyFirstSpec) describe(@"Basic Arithmetic", ^{ it(@"can increment 12",^{ [[theValue(12+1) should] equal:theValue(13)]; }); }); SPEC_END ExampleSpec.m

Slide 46

Slide 46 text

12+1 does equal 13 does 12*2 equal 24?

Slide 47

Slide 47 text

#import "Kiwi.h" SPEC_BEGIN(MyFirstSpec) describe(@"Basic Arithmetic", ^{ it(@"can increment 12",^{ [[theValue(12+1) should] equal:theValue(13)]; }); }); SPEC_END ExampleSpec.m

Slide 48

Slide 48 text

testing ‘real’ app code parsing JSON

Slide 49

Slide 49 text

Introducing: Run2Bart

Slide 50

Slide 50 text

parsing JSON

Slide 51

Slide 51 text

@implementation Station + (NSArray *)loadStations:(NSArray *)rawStations { NSMutableArray *stations = [NSMutableArray array]; for(NSDictionary *rawStation in rawStations){ Station *station = [[Station alloc] initWithName:rawStation[@"name"] abbr:rawStation[@"abbr"]]; [stations addObject:station]; } return stations; } - (id)initWithName:(NSString *)name abbr:(NSString *)abbr { self = [super init]; if (self) { _name = [name copy]; ! ! _abbr = [abbr copy]; } return self; } @end Station.m

Slide 52

Slide 52 text

system under test in out

Slide 53

Slide 53 text

[ { “name”:”foo”, ... }, {...} ] Station loadStations

Slide 54

Slide 54 text

describe(@"Station", ^{ it(@"loads from JSON correctly",^{ NSArray *rawStations = @[ @{@"abbr":@"s1",@"name":@"station one"}, @{@"abbr":@"s2",@"name":@"station two"}, ]; NSArray *stations = [Station loadStations:rawStations]; [[theValue(stations.count) should] equal:theValue(2)]; [[[stations[0] abbr] should] equal:@"s1"]; [[[stations[0] name] should] equal:@"station one"]; [[[stations[1] abbr] should] equal:@"s2"]; [[[stations[1] name] should] equal:@"station two"]; }); }); StationSpec.m

Slide 55

Slide 55 text

Arrange, Act, Assert

Slide 56

Slide 56 text

describe(@"Station", ^{ it(@"loads from JSON correctly",^{ NSArray *rawStations = @[ @{@"abbr":@"s1",@"name":@"station one"}, @{@"abbr":@"s2",@"name":@"station two"}, ]; NSArray *stations = [Station loadStations:rawStations]; [[theValue(stations.count) should] equal:theValue(2)]; [[[stations[0] abbr] should] equal:@"s1"]; [[[stations[0] name] should] equal:@"station one"]; [[[stations[1] abbr] should] equal:@"s2"]; [[[stations[1] name] should] equal:@"station two"]; }); }); arrange

Slide 57

Slide 57 text

describe(@"Station", ^{ it(@"loads from JSON correctly",^{ NSArray *rawStations = @[ @{@"abbr":@"s1",@"name":@"station one"}, @{@"abbr":@"s2",@"name":@"station two"}, ]; NSArray *stations = [Station loadStations:rawStations]; [[theValue(stations.count) should] equal:theValue(2)]; [[[stations[0] abbr] should] equal:@"s1"]; [[[stations[0] name] should] equal:@"station one"]; [[[stations[1] abbr] should] equal:@"s2"]; [[[stations[1] name] should] equal:@"station two"]; }); }); act

Slide 58

Slide 58 text

describe(@"Station", ^{ it(@"loads from JSON correctly",^{ NSArray *rawStations = @[ @{@"abbr":@"s1",@"name":@"station one"}, @{@"abbr":@"s2",@"name":@"station two"}, ]; NSArray *stations = [Station loadStations:rawStations]; [[theValue(stations.count) should] equal:theValue(2)]; [[[stations[0] abbr] should] equal:@"s1"]; [[[stations[0] name] should] equal:@"station one"]; [[[stations[1] abbr] should] equal:@"s2"]; [[[stations[1] name] should] equal:@"station two"]; }); }); assert

Slide 59

Slide 59 text

describe(@"Station", ^{ it(@"loads from JSON correctly",^{ ////////////////// // Arrange NSArray *rawStations = @[ @{@"abbr":@"s1",@"name":@"station one"}, @{@"abbr":@"s2",@"name":@"station two"}, ]; ////////////////// // Act NSArray *stations = [Station loadStations:rawStations]; ////////////////// // Assert [[theValue(stations.count) should] equal:theValue(2)]; [[[stations[0] abbr] should] equal:@"s1"]; [[[stations[0] name] should] equal:@"station one"]; [[[stations[1] abbr] should] equal:@"s2"]; [[[stations[1] name] should] equal:@"station two"]; }); });

Slide 60

Slide 60 text

Given, When, Then

Slide 61

Slide 61 text

describe(@"Station", ^{ it(@"loads from JSON correctly",^{ ////////////////// // Given NSArray *rawStations = @[ @{@"abbr":@"s1",@"name":@"station one"}, @{@"abbr":@"s2",@"name":@"station two"}, ]; ////////////////// // When NSArray *stations = [Station loadStations:rawStations]; ////////////////// // Then [[theValue(stations.count) should] equal:theValue(2)]; [[[stations[0] abbr] should] equal:@"s1"]; [[[stations[0] name] should] equal:@"station one"]; [[[stations[1] abbr] should] equal:@"s2"]; [[[stations[1] name] should] equal:@"station two"]; }); });

Slide 62

Slide 62 text

another simple test displaying estimated departures

Slide 63

Slide 63 text

5 “5 mins” etdToDisplay

Slide 64

Slide 64 text

#import "Kiwi.h" #import "UpcomingDeparture.h" SPEC_BEGIN(UpcomingDepartureSpec) describe(@"[UpcomingDeparture etdToDisplay]", ^{ it(@"is correct for an etd of 5",^{ UpcomingDeparture *upcomingDeparture = [[UpcomingDeparture alloc] initWithDestinationName:@"blah" etd:@(5)]; [[[upcomingDeparture etdToDisplay] should] equal:@"5 mins"]; }); }); SPEC_END UpcomingDepartureSpec.m

Slide 65

Slide 65 text

- (NSString *) etdToDisplay{ return [NSString stringWithFormat:@"%@ mins", self.etdInMinutes]; } UpcomingDeparture.m

Slide 66

Slide 66 text

5 “5 mins” etdToDisplay

Slide 67

Slide 67 text

etdToDisplay 1 “1 min” 5 “5 mins”

Slide 68

Slide 68 text

etdToDisplay 0 “now” 5 “5 mins” 1 “1 min”

Slide 69

Slide 69 text

Let’s do some TDD!

Slide 70

Slide 70 text

describe(@"[UpcomingDeparture etdToDisplay]", ^{ it(@"is correct for an etd of 5",^{ UpcomingDeparture *upcomingDeparture = [[UpcomingDeparture alloc] initWithDestinationName:@"blah" etd:@(5)]; [[[upcomingDeparture etdToDisplay] should] equal:@"5 mins"]; }); it(@"is correct for an etd of 1",^{ UpcomingDeparture *upcomingDeparture = [[UpcomingDeparture alloc] initWithDestinationName:@"blah" etd:@(1)]; [[[upcomingDeparture etdToDisplay] should] equal:@"1 min"]; }); it(@"is correct for an etd of 0",^{ UpcomingDeparture *upcomingDeparture = [[UpcomingDeparture alloc] initWithDestinationName:@"blah" etd:@(0)]; [[[upcomingDeparture etdToDisplay] should] equal:@"now"]; }); }); UpcomingDepartureSpec.m

Slide 71

Slide 71 text

edge-cases made easier

Slide 72

Slide 72 text

~ BREAK? ~

Slide 73

Slide 73 text

testing UIKit code

Slide 74

Slide 74 text

$> git checkout sl-3 $> git clean -dxf 1: Close XCode 2: 3: Open Run2Bart.xcworkspace

Slide 75

Slide 75 text

- (id)initForStation:(Station *)station { self = [super init]; if (self) { self.station = station; self.title = station.name; self.bartClient = [AppDelegate sharedInstance].bartClient; } return self; } UpcomingDeparturesViewController.m

Slide 76

Slide 76 text

SPEC_BEGIN(UpcomingDeparturesViewControllerSpec) describe( @"UpcomingDeparturesViewController ", ^{ it( @"has the station's name as the title", ^{ // Given Station *theStation = [[Station alloc] initWithName:@"station name" abbr:@"station-abbr"]; UpcomingDeparturesViewController *theDeparturesVC = [[UpcomingDeparturesViewController alloc] initForStation:theStation]; // Then [[theDeparturesVC.title should] equal:@"station name"]; }); // ... UpcomingDeparturesViewControllerSpec.m

Slide 77

Slide 77 text

UIKit code is still just code

Slide 78

Slide 78 text

testing UIKit code rendering UITableViewCells

Slide 79

Slide 79 text

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UpcomingDeparture *departure = [self.departures objectAtIndex:indexPath.row]; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if( !cell ) cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier]; cell.textLabel.font = [UIFont systemFontOfSize:18.0]; cell.detailTextLabel.font = [UIFont systemFontOfSize:24.0]; cell.textLabel.text = departure.destinationName; cell.detailTextLabel.text = departure.etdToDisplay; return cell; } UpcomingDeparturesViewController.m

Slide 80

Slide 80 text

describe(@"rendering departures", ^{ it( @"renders a table view cell for each departure", ^{ // Given UITableView *ignoredTableView = nil; Station *someStation = [[Station alloc] initWithName:@"station name" abbr:@"station-abbr"]; UpcomingDeparturesViewController *departuresVC = [[UpcomingDeparturesViewController alloc] initForStation:someStation]; NSArray *departures = @[ [[UpcomingDeparture alloc] initWithDestinationName:@"dest 1" etd:@(0)], [[UpcomingDeparture alloc] initWithDestinationName:@"dest 2" etd:@(1)], [[UpcomingDeparture alloc] initWithDestinationName:@"dest 3" etd:@(2)] ]; departuresVC.departures = departures; // When NSInteger numSections = [departuresVC numberOfSectionsInTableView:ignoredTableView]; NSInteger numRows = [departuresVC tableView:ignoredTableView numberOfRowsInSection:0]; // Then [[theValue(numSections) should] equal:theValue(1)]; [[theValue(numRows) should] equal:theValue(3)]; }); }); UpcomingDeparturesViewControllerSpec.m

Slide 81

Slide 81 text

your turn test that: table view cells have the right data

Slide 82

Slide 82 text

hints [departureVC tableView:cellForRowAtIndexPath:] tableViewCell.textLabel.text tableViewCell.detailTextLabel.text BREAK after this

Slide 83

Slide 83 text

~ BREAK? ~

Slide 84

Slide 84 text

test doubles (mocks/stubs)

Slide 85

Slide 85 text

$> git checkout sl-4 $> git clean -dxf 1: Close XCode 2: 3: Open Run2Bart.xcworkspace

Slide 86

Slide 86 text

UpcomingDeparturesViewController.m - (void)viewWillAppear:(BOOL)animated{ [self refreshUpcomingDepartures]; } - (void) refreshUpcomingDepartures{ [self.refreshControl beginRefreshing]; [self.bartClient fetchUpcomingDeparturesForStation:self.station success:^(NSArray *departures) { [self.refreshControl endRefreshing]; self.departures = departures; [self.tableView reloadData]; } failure:^(NSError *error) { [self.refreshControl endRefreshing]; }]; }

Slide 87

Slide 87 text

Dependencies in Unit Tests

Slide 88

Slide 88 text

API UI Business Logic

Slide 89

Slide 89 text

API UI Business Logic SUT

Slide 90

Slide 90 text

API UI Business Logic SUT

Slide 91

Slide 91 text

API UI Business Logic SUT

Slide 92

Slide 92 text

API UI Business Logic SUT TD TD

Slide 93

Slide 93 text

SUT TD TD

Slide 94

Slide 94 text

API UI Business Logic SUT

Slide 95

Slide 95 text

API UI Business Logic SUT View Controller

Slide 96

Slide 96 text

API UI Business Logic SUT BartClient View Controller

Slide 97

Slide 97 text

API UI Business Logic SUT TD

Slide 98

Slide 98 text

API UI Business Logic SUT TD View Controller

Slide 99

Slide 99 text

API UI Business Logic SUT TD Spy BartClient View Controller

Slide 100

Slide 100 text

- (void)viewWillAppear:(BOOL)animated{ [self refreshUpcomingDepartures]; } - (void) refreshUpcomingDepartures{ [self.refreshControl beginRefreshing]; [self.bartClient fetchUpcomingDeparturesForStation:self.station success:^(NSArray *departures) { [self.refreshControl endRefreshing]; self.departures = departures; [self.tableView reloadData]; } failure:^(NSError *error) { [self.refreshControl endRefreshing]; }]; } UpcomingDeparturesViewController.m

Slide 101

Slide 101 text

@interface SpyBartClient : NSObject{ BOOL _fetchWasCalled; } @end @implementation SpyBartClient - (id)init { self = [super init]; if (self) { _fetchWasCalled = NO; } return self; } - (void)fetchUpcomingDeparturesForStation:(Station *)station success:(FetchSuccessBlock)success failure:(FetchFailureBlock)failure{ _fetchWasCalled = YES; } - (BOOL)fetchUpcomingDeparturesWasCalled{ return _fetchWasCalled; } @end UpcomingDeparturesViewControllerSpec.m

Slide 102

Slide 102 text

describe(@"the VC's view appearing", ^{ it( @"asks the api client to load the upcoming departures", ^{ SpyBartClient *testDoubleBartClient = [[SpyBartClient alloc] init]; departuresVC.bartClient = testDoubleBartClient; [departuresVC viewWillAppear:YES]; [[theValue([testDoubleBartClient fetchUpcomingDeparturesWasCalled]) should] beTrue]; }); }); UpcomingDeparturesViewControllerSpec.m

Slide 103

Slide 103 text

API UI Business Logic SUT TD Spy BartClient View Controller

Slide 104

Slide 104 text

from hand-rolled to dynamic

Slide 105

Slide 105 text

@interface SpyBartClient : NSObject{ BOOL _fetchWasCalled; } @end @implementation SpyBartClient - (id)init { self = [super init]; if (self) { _fetchWasCalled = NO; } return self; } - (void)fetchUpcomingDeparturesForStation:(Station *)station success:(FetchSuccessBlock)success failure:(FetchFailureBlock)failure{ _fetchWasCalled = YES; } - (BOOL)fetchUpcomingDeparturesWasCalled{ return _fetchWasCalled; } @end UpcomingDeparturesViewControllerSpec.m

Slide 106

Slide 106 text

UpcomingDeparturesViewControllerSpec.m id mockBartClient = [KWMock mockForProtocol:@protocol(BartClient)];

Slide 107

Slide 107 text

UpcomingDeparturesViewControllerSpec.m it( @"asks the api client to load the upcoming departures", ^{ id mockBartClient = [KWMock mockForProtocol:@protocol(BartClient)]; departuresVC.bartClient = mockBartClient; [[mockBartClient should] receive:@selector(fetchUpcomingDeparturesForStation:success:failure:) andReturn:nil]; [departuresVC viewWillAppear:YES]; });

Slide 108

Slide 108 text

it( @"asks the api client to load the upcoming departures", ^{ id mockBartClient = [KWMock mockForProtocol:@protocol(BartClient)]; departuresVC.bartClient = mockBartClient; [[mockBartClient should] receive:@selector(fetchUpcomingDeparturesForStation:success:failure:) andReturn:nil]; [departuresVC viewWillAppear:YES]; }); it( @"asks the api client to load the upcoming departures", ^{ SpyBartClient *testDoubleBartClient = [[SpyBartClient alloc] init]; departuresVC.bartClient = testDoubleBartClient; [departuresVC viewWillAppear:YES]; [[theValue([testDoubleBartClient fetchUpcomingDeparturesWasCalled] should] beTrue]; }); hand-rolled dynamic

Slide 109

Slide 109 text

verifying what has been sent to a test double

Slide 110

Slide 110 text

- (void)viewWillAppear:(BOOL)animated{ [self refreshUpcomingDepartures]; } - (void) refreshUpcomingDepartures{ [self.refreshControl beginRefreshing]; [self.bartClient fetchUpcomingDeparturesForStation:self.station success:^(NSArray *departures) { [self.refreshControl endRefreshing]; self.departures = departures; [self.tableView reloadData]; } failure:^(NSError *error) { [self.refreshControl endRefreshing]; }]; } UpcomingDeparturesViewController.m

Slide 111

Slide 111 text

UpcomingDeparturesViewControllerSpec.m it( @"asks the api client to load the upcoming departures for the right station", ^{ id mockBartClient = [KWMock mockForProtocol:@protocol(BartClient)]; departuresVC.bartClient = mockBartClient; [[[mockBartClient should] receive] fetchUpcomingDeparturesForStation:station success:any() failure:any()]; [departuresVC viewWillAppear:YES]; });

Slide 112

Slide 112 text

another way to think about mocks/stubs

Slide 113

Slide 113 text

system under test in out

Slide 114

Slide 114 text

D e p e n d e n c y system under test indirect output indirect input direct input direct output T e s t

Slide 115

Slide 115 text

API UI Business Logic SUT BartClient View Controller

Slide 116

Slide 116 text

API UI Business Logic SUT

Slide 117

Slide 117 text

usiness ogic SUT SUT TD Test

Slide 118

Slide 118 text

D e p e n d e n c y system under test indirect output indirect input direct input direct output T e s t values passed to dependency via method call values returned from call to dependency

Slide 119

Slide 119 text

~ BREAK? ~

Slide 120

Slide 120 text

DRYing up your test code

Slide 121

Slide 121 text

$> git checkout sl-3 $> git clean -dxf 1: Close XCode 2: 3: Open Run2Bart.xcworkspace

Slide 122

Slide 122 text

Don’t Repeat Yourself

Slide 123

Slide 123 text

describe( @"UpcomingDeparturesViewController ", ^{ it( @"has the station's name as the title", ^{ // Given Station *theStation = [[Station alloc] initWithName:@"station name" abbr:@"station-abbr"]; UpcomingDeparturesViewController *theDeparturesVC = [[UpcomingDeparturesViewController alloc] initForStation:theStation]; // Then [[theDeparturesVC.title should] equal:@"station name"]; }); // ... UpcomingDeparturesViewControllerSpec.m

Slide 124

Slide 124 text

describe( @"UpcomingDeparturesViewController ", ^{ it( @"has the station's name as the title", ^{ // Given Station *theStation = [[Station alloc] initWithName:@"station name" abbr:@"station-abbr"]; UpcomingDeparturesViewController *theDeparturesVC = [[UpcomingDeparturesViewController alloc] initForStation:theStation]; // Then [[theDeparturesVC.title should] equal:@"station name"]; }); // ... UpcomingDeparturesViewControllerSpec.m

Slide 125

Slide 125 text

describe( @"UpcomingDeparturesViewController ", ^{ __block Station *station; __block UpcomingDeparturesViewController *departuresVC; beforeEach(^{ station = [[Station alloc] initWithName:@"station name" abbr:@"station-abbr"]; departuresVC = [[UpcomingDeparturesViewController alloc] initForStation:station]; }) it( @"has the station's name as the title", ^{ // Then [[departuresVC.title should] equal:station.name]; }); // ... UpcomingDeparturesViewControllerSpec.m

Slide 126

Slide 126 text

your turn: DRY it up UpcomingDeparturesViewControllerSpec.m introduce a beforeEach block change tests in the file to take advantage of it

Slide 127

Slide 127 text

describe( @"UpcomingDeparturesViewController ", ^{ __block Station *station; __block UpcomingDeparturesViewController *departuresVC; beforeEach(^{ station = [[Station alloc] initWithName:@"station name" abbr:@"station-abbr"]; departuresVC = [[UpcomingDeparturesViewController alloc] initForStation:station]; }) it( @"has the station's name as the title", ^{ // Then [[departuresVC.title should] equal:station.name]; }); // ... UpcomingDeparturesViewControllerSpec.m

Slide 128

Slide 128 text

how unit-testing influences design

Slide 129

Slide 129 text

No content

Slide 130

Slide 130 text

testable code is also loosely coupled and highly coherent

Slide 131

Slide 131 text

most of your code shouldn’t be UIKit code

Slide 132

Slide 132 text

Test-Driven Development

Slide 133

Slide 133 text

Test-Driven Design

Slide 134

Slide 134 text

TDD works best with fast tests

Slide 135

Slide 135 text

extra stuff - xctool - specta/expecta