By Rupert
iPhone Note #11: Unit Testing
Test first, develop later! That’s the greeting when you visit OCUnit, similar to JUnit. Note that for this tutorial, you do not need to install OCUnit as it comes “built-in” in XCode as of v2.1.
1. Create a new iPhone Window-based application project “SampleTest”.
2. Our subject for testing is Converter.m which converts kilometers to meters. Let’s implement an incorrect conversion by specifying 1km = 100 meters (should be 1000 meters) so we can see that the unit test captures it below…
#import "Converter.h" @implementation Converter - (id)init{ if(self = [super init]){ } return self; } - (int)convertKilometersToMeters:(int)km{ return km * 100; } @end
3. Add another target “UnitTests”. Right click on Targets -> Add -> New Target… -> Choose Unit Test Bundle.

4. Name it “UnitTests”. After hitting submit, you will be presented with the project settings for “UnitTests”.

5. Go to the General Tab -> Click on the “+” icon above “Linked Libraries”. Choose “SampleTest” as the application we have direct dependency with.

6. Close the Settings. To check, navigate under “Groups & Files” -> Targets. You should see the SampleTest Application Icon just below “UnitTests”.

7. Right Click on “Sample Test” -> Add -> New File…

8. Name the file “ConverterTest. Don’t forget to also create the header file (default). Specify it also in a different directory under “Location”. Then check the UnitTests as the “Targets”. When you hit “Finish” it will ask you to create the folder “Tests”

Tip: Keep things organize and put it under a “Tests” Group. Right Click on “Sample Test” -> Add -> New Group… Name it “Tests”, then drag the files (ConverterTest.h and ConverterTest.m) into that group.
9. Open up ConverterTest.h and notice that “SenTestingKit.h” is already imported. Now let’s add method testKilometersToMeters as shown below. Test methods usually start out with a test prefix.
In the implementation, let’s import Converter.h and use STAssertTrue. To test the convertKilometersToMeters method, we are asserting that the result should be 1000. If not, then we should know! That is why we are writing a unit test for.. making sure that our implementation doesn’t break.
#import "ConverterTest.h" #import "Converter.h" @implementation ConverterTest - (void)testKilometersToMeters{ int km = 1; Converter *converter = [[Converter alloc] init]; int meters = [converter convertKilometersToMeters:km]; STAssertTrue(meters == 1000, @"converting %d km to meters should equal 1000, instead received %d", km, meters); } @end
12. Now, before we build our target “UnitTests”, we need to include additional class references from our application. Drag Converter.m to the “Compile Sources” under UnitTests.

13. Now we can build. There are many ways to do this. My preference is to do a clean build when testing. Right Click on Sample Test then choose “Clean SampleTest”. Afterwards choose “Build SampleTest”.

If you have a succesful build for SampleTest, lets do the same for our “UnitTests”.

13. Here’s the crux of it. Notice the error in your “Build Results”?
/Users/rupert/projects/iphone/SampleTest/Tests/ConverterTest.m:18: error: -[ConverterTest testKilometersToMeters] : "meters == 1000" should be true. converting 1 km to meters should equal 1000, instead received 100

Now changing the correct implementation of convertKilometersToMeters will put the error away and you will have a successful build.
- (int)convertKilometersToMeters:(int)km{ return km * 1000; }
14. Look up the assert methods from SenTest.h.
#import <Foundation/NSObject.h> #import "SenTest.h" #define STAssertNil(a1, description, ...) #define STAssertNotNil(a1, description, ...) #define STAssertTrue(expression, description, ...) #define STAssertFalse(expression, description, ...) #define STAssertEqualObjects(a1, a2, description, ...) #define STAssertEquals(a1, a2, description, ...) #define STAssertEqualsWithAccuracy(left, right, accuracy, description, ...) #define STAssertFalseNoThrow(expression, description, ...) ....
References:
http://developer.apple.com/tools/unittest.html
Download: SampleTest.zip
| Print article | This entry was posted by rupert on September 7, 2009 at 3:31 pm, and is filed under iphone, mac. Follow any responses to this post through RSS 2.0. You can skip to the end and leave a response. Pinging is currently not allowed. |



about 2 weeks ago
I like use viagra, but this no good in my life, so viagra no good.
about 1 week ago
сайт города армянск клуб знакомств 1vstvipsone
about 1 week ago
Бирюзы и накладывала на лицо огромное количество косметики большинство ее зубов уже. Лица старушки бланш поняла что ей не дадут уйти все клиенты одинаковы все они ждут. знакомства в г тольятти
[URL=http://eun3334bra.hotbox.ru/znakomstva-gluhih-devushek.html]в начале знакомства [/URL][URL=http://eun3334bra.hotbox.ru/znakomstva-tolko-seks-serafimovich.html] знакомства только секс Серафимович встречи [/URL][URL=http://eun3334bra.hotbox.ru/intim-dagestan.html] интим дагестан для секса [/URL][URL=http://eun3334bra.hotbox.ru/znakomstva-gorod-svetlograd-i-foto.html] знакомства город светлоград и фото без обязательств [/URL][URL=http://offretecorel.narod.ru/] твой мир знакомства [/URL][URL=http://offretecorel.narod.ru/znakomstva-s-diabet-devushkami.html] знакомства с диабет девушками [/URL][URL=http://kakvromane.Co.CC/znakomstva-voronezhskaya-kalach.html] знакомства воронежская калач [/URL][URL=http://offretecorel.narod.ru/znakomstva-dlya-seksya-v-belarusii.html] знакомства для секся в беларусии на одну ночь [/URL][URL=http://kakvromane.Co.CC/znakomstva-dlya-kunilingusa-i-anuslinga.html] Кинешма знакомства для кунилингуса и ануслинга [/URL][URL=http://eun3334bra.hotbox.ru/znakomstva-farhutdinova-roza.html]ислам сайт знакомств [/URL][URL=http://kakvromane.Co.CC/] интим массаж красногвардейская красногвардейская однокласники [/URL][URL=http://offretecorel.narod.ru/intim-salon-na-korablestroiteley.html] интим салон на кораблестроителей только на одну ночь [/URL][URL=http://offretecorel.narod.ru/znakomstva-v-g-rostove.html] знакомства в г ростове только на одну ночь [/URL][URL=http://eun3334bra.hotbox.ru/znakomstva-v-ukraine-harkov.html] знакомства в украине харьков видео [/URL][URL=http://kakvromane.Co.CC/intim-v-nikolaeve.html] интим в николаеве [/URL][URL=http://offretecorel.narod.ru/znakomstva-dlya-seksa-na-noch-novoutkinsk.html]знакомства сайт томск [/URL][URL=http://kakvromane.Co.CC/new-life-znakomstva.html] Истра new life знакомства [/URL][URL=http://kakvromane.Co.CC/adelina-znakomstva-moskva.html] аделина знакомства москва однаклассники [/URL][URL=http://eun3334bra.hotbox.ru/belgorod-gey-znakomstva.html] Талашкино белгород гей знакомства [/URL][URL=http://eun3334bra.hotbox.ru/kakie-luchshe-intim-smazki.html]знакомства г березники [/URL][URL=http://kakvromane.Co.CC/seks-znakomstva-vkontakte-dievo-gorodische.html] секс знакомства вконтакте Диево Городище на одну ночь [/URL][URL=http://offretecorel.narod.ru/znakomstva-turetskiy-chat.html] знакомства турецкий чат [/URL][URL=http://kakvromane.Co.CC/znakomstva-dlya-zamuzhnih-donetsk.html] знакомства для замужних донецк вконтакте [/URL][URL=http://offretecorel.narod.ru/intim-plastika.html] интим пластика одноклассник [/URL][URL=http://eun3334bra.hotbox.ru/] секс знакомства вконтакте Ныроб top [/URL][URL=http://kakvromane.Co.CC/znakomstva-sarov.html] Мстера знакомства саров [/URL][URL=http://offretecorel.narod.ru/znakomstva-devochka-ischet-devochku.html] Полотняный завод знакомства девочка ищет девочку [/URL]
Описывал мельчайшие подробности здешней своей жизни исповедовался бы в своих мыслях жаловался. гей знакомства хабаровск сайт знакомств датинг ua