200 likes | 356 Views
Test Driven Development . Writing better code. By Stuart Mackey. Who is this guy…. …and why should I listen?. What will we talk about?. What is Unit testing? What is TDD? What are the benefits? How do you unit test in Xcode? Testing frameworks. What is Unit testing?.
E N D
Test Driven Development Writing better code By Stuart Mackey
What will we talk about? • What is Unit testing? • What is TDD? • What are the benefits? • How do you unit test in Xcode? • Testing frameworks.
What is Unit testing? Unit testing is a method by which individual units of source code are tested to determine if they are fit for use. - Wikipedia
What is a unit test? • Simply a method with three parts • Create the object under test • Exercise the object • Make an assertion
Examples – Unit Test • (void)testCreateInstanceWithType { Foo *foo= [[Foo alloc] init]; foo.type = @”bar”; STAssertEqualStrings (foo.type, @”bar”, @”Type not bar”); }
Examples - Asserts • STAssertNotNULL • STAssertNULL • STAssertNotEquals • STAssertEquals • STAssertGreaterThan • STAssertLessThan • STAssertEqualStrings • STAssertNotEqualStrings
Examples – Unit Test • (void)testBruteForce { Foo *foo= [[Foo alloc] init]; for (int i=0; i<100; i++) { [foo setValue:i]; if (i== 50) { STAssertEqualStrings (foo.type, @”Type 50”, @”Type 50 not set”); } else { STAssertEqualStrings (foo.type, @”Other Type”, @”Other not set”); } } }
Demo Unit testing and Xcode.
TDD- Example Date entry and validation
TDD – Think differently Before After OnClick { CalendarEntry *entry = [[CalendarEntry alloc] init]; entry.startDate = dateField.text; if ([entry isValidDate]) { self.errorMsg.text = entry.errorMsg; } } OnClick { if (![self dateValid:dateField.text]) { self.errorMsg.text = @”Invalid date”; } }
Demo Thinking in objects
What are the benefits? • Less ad-hoc testing • Fewer bugs • Cleaner code • Easier to maintain
Testing Frameworks • All examples so far have used SimpleUnitTest • Others include OCUnit, GHUnit. • Varying levels of integration with Xcode.
Useful links • http://en.wikipedia.org/wiki/Unit_testing • https://github.com/gabriel/gh-unit • http://mobileorchard.com/ocunit-integrated-unit-testing-in-xcode/ • http://cbess.blogspot.com/2010/05/simple-iphone-ipad-unit-test.html • http://www.mulle-kybernetik.com/software/OCMock/
Contacts e: stuart@paperbagltd.com t: @stuartmackey w: http://www.paperbagltd.com