Apr 18 2011

iPhone Unit Test tips: Read a file in your test

Category: bdd,objective-cgiordano scalzo @ 12:44 pm

Very often I need to unit test something read from a file, but it seems very difficult to accomplish this simple task in iOS, so usually I give up.
But today I felt was a good day to find a solution ;-)
In my code I want to read a JSon data from a file, so I wrote a simple test:

describe(@"Conference", ^{
    it(@"loads given a filename", ^{
        Conference *conference = [[Conference alloc]initWithFile:@"talks_with_three_tracks"];
        [[theValue([conference hasData]) should] beTrue];

with a simple init method:

-(id)initWithFile:(NSString *)filename{
    if ((self = [super init])) {
        NSString* path = [[NSBundle mainBundle] pathForResource:filename ofType:@"json"];
        NSError *error;
        NSString* talksString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
        talks = [talksString JSONValue];
    return self;

    return talks!=nil;

Unfortunately it doesn’t work :-( , because path is nil;
But here it isthe solution:
instead of using [NSBundle mainBundle], we should use the bundle associated with our class:

        NSString *path = [[NSBundle bundleForClass:[Conference class]] pathForResource:filename ofType:@"json"];

Simple and neat: thank you StackOverflow ;-)

Technorati Tags: , ,

Tags: , ,