2013-05-15 10 views
11

Sto provando a scrivere test unitari per la convalida JSON (poiché l'app si basa pesantemente su JSON da un'API di riposo).Come leggere un file JSON locale per il test

Ho un file locale che contiene semplice JSON: "goodFeaturedJson.txt"

il contenuto:

{ 
    "test": "TEST" 
} 

il banco di prova:

- (void)testJsonIsValid 
{ 
    Featured *featured = [Featured new]; 

    NSString* filepath = [[NSBundle mainBundle]pathForResource:@"goodFeaturedJson" ofType:@"text"]; 

    NSData *data = [NSData dataWithContentsOfFile:filepath]; 

    NSString *jsonString = [[NSString alloc] initWithContentsOfFile:filepath encoding:NSUTF8StringEncoding error:nil];//[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 

    NSLog(@"The json string is: %@", jsonString); 

    id JSON = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]; 

    STAssertTrue([featured jsonIsValid:JSON], @"Featured Data is NOT valid...");  
} 

il test fallisce ogni volta. La console stampa:

The json string is: (null) 

Perché? So perché il test sta fallendo, poiché chiaramente se i dati sono nulli/nulli non ci sarà nessun json valido, e il validatore si romperà (cosa che dovrebbe essere se non valido).

Deve esserci qualcosa di semplice che mi è sfuggito qui, qualche idea?

+0

dovrebbe ofType essere 'ofType: @" txt "'? –

+0

La stringa è ancora null se lo faccio. Ho provato il testo e "json" come tipo. Il risultato sembra essere sempre lo stesso e non sono sicuro del perché. –

+0

Che cosa dice l'errore (che a quanto pare non si preoccupa di controllare)? –

risposta

19

In un test di unità probabilmente si desidera utilizzare [NSBundle bundleForClass:[self class]] e non [NSBundle mainBundle]. Questo perché il test unitario non è un'app standalone. Con mainBundle si ottiene qualcosa come /Applications/Xcode.app/Contents/Developer/Tools, ma usando bundleForClass si ottiene il pacchetto in cui si trova la classe di test dell'unità.

+0

Dannazione, non lo sapevo su NSBundle; Grazie! (Questo ha risolto tutto). –

4

In Swift

Swift 3 e sopra

guard let pathString = Bundle(for: type(of: self)).path(forResource: "UnitTestData", ofType: "json") else { 
    fatalError("UnitTestData.json not found") 
} 

guard let jsonString = try? NSString(contentsOfFile: pathString, encoding: String.Encoding.utf8.rawValue) else { 
    fatalError("Unable to convert UnitTestData.json to String") 
} 

print("The JSON string is: \(jsonString)") 

guard let jsonData = jsonString.data(using: String.Encoding.utf8.rawValue) else { 
    fatalError("Unable to convert UnitTestData.json to NSData") 
} 

guard let jsonDictionary = try? JSONSerialization.jsonObject(with: jsonData, options: []) as? [String:AnyObject] else { 
    fatalError("Unable to convert UnitTestData.json to JSON dictionary") 
} 

print("The JSON dictionary is: \(jsonDictionary)") 

Swift 2,2

guard let pathString = NSBundle(forClass: self.dynamicType).pathForResource("UnitTestData", ofType: "json") else { 
     fatalError("UnitTestData.json not found") 
    } 

    guard let jsonString = try? NSString(contentsOfFile: pathString, encoding: NSUTF8StringEncoding) else { 
     fatalError("Unable to convert UnitTestData.json to String") 
    } 

    print("The JSON string is: \(jsonString)") 

    guard let jsonData = jsonString.dataUsingEncoding(NSUTF8StringEncoding) else { 
     fatalError("Unable to convert UnitTestData.json to NSData") 
    } 

    guard let jsonDictionary = try? NSJSONSerialization.JSONObjectWithData(jsonData, options: []) as? [String:AnyObject] else { 
     fatalError("Unable to convert UnitTestData.json to JSON dictionary") 
    } 

    print("The JSON dictionary is: \(jsonDictionary)") 

* Questa incorpora la risposta di Tom Harrington, che è in Objective C