Sometimes it’s handy to parse a json file as part of a unit test. Here’s how you it.

First create a test file containing the json you would like to parse:

job.json
{
    "id":"1",
    "state":"entered"
}

Second, create a helper class to find your test file, and return an id object containing the json:

TestingHelper.h

#import <Foundation/Foundation.h>

@interface TestingHelper : NSObject
+ (id)dataFromJSONFileNamed:(NSString *)fileName;
@end

TestingHelper.m

#import "TestingHelper.h"
#import "JSONKit.h"

@implementation TestingHelper

+ (id)dataFromJSONFileNamed:(NSString *)fileName
{
    //    NSString *resource = [[NSBundle mainBundle] pathForResource:fileName ofType:@"json"];
    
    NSBundle *bundle = [NSBundle bundleForClass:[self class]];
    NSString *resource = [bundle pathForResource:fileName ofType:@"json"];
    
    if (NSClassFromString(@"NSJSONSerialization")) {
        NSInputStream *inputStream = [NSInputStream inputStreamWithFileAtPath:resource];
        [inputStream open];
        
        return [NSJSONSerialization JSONObjectWithStream:inputStream options:0 error:nil];
    } else {
        NSData *jsonData = [NSData dataWithContentsOfFile:resource];
        return [jsonData objectFromJSONData];
    }
}

@end

The important lines are these ones:

    NSBundle *bundle = [NSBundle bundleForClass:[self class]];
    NSString *resource = [bundle pathForResource:fileName ofType:@"json"];

These search your unit test bundle for the test file. Don’t do this.

NSString *resource = [[NSBundle mainBundle] pathForResource:fileName ofType:@"json"];

Unless you know what you are doing and have explicitly included that file to be copied to the bundle.

Then just call your test and make your assertions!

- (void)testJobPopulationWithJson
{
    NSArray *jsonArray = [TestingHelper dataFromJSONFileNamed:@"job"];
    [[JobRepository sharedRepository] extractJobsFromJson:jsonArray];

    // make your assertions
    STAssertTrue(1 == [[[JobRepository sharedRepository] enteredJobs] count], @"1 entered job.");
}

To test that your are getting your data from your file, set a break point and print out the array:

Links that help:
http://stackoverflow.com/questions/1879247/why-cant-code-inside-unit-tests-find-bundle-resources

And thank you to Nick Waynik (@n_dubbs) for this tip.

Update

For a video walkthrough of how to do this see:

http://academy.robotsandpencils.com/episodes/14-json-unit-tests