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:


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


#import <Foundation/Foundation.h>

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


#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];


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:

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


For a video walkthrough of how to do this see: