あるテキストファイルを読むヘルパークラスの動作確認をするために、たまにはテストでも書くかと、安易な気持ちで書き始めたら詰まってしまった。
端的に述べると、XcodeのTestプロジェクト中で[[NSBundle mainBundle] pathForResouce]を使ってもnilしか返ってこず、かわりに[[NSBundle bundleForClass:[self class]] pathForResouce]とする必要があるようです。(self はテストケースのインスタンス.)
ヘルパークラス内でmainBundleを利用してたりする場合要注意。
// こっちはfilePathを取得できる
-(void)testExistFile
{
NSString* filePath = [[NSBundle bundleForClass:[self class]] pathForResource:@"Test" ofType:@"txt"];
XCTAssertNotNil(filePath, @"%@", filePath);
}
// こっちは取得できない。
-(void)testExistFileUseMainBundle
{
NSString* filePath = [[NSBundle mainBundle] pathForResource:@"Test" ofType:@"txt"];
XCTAssertNil(filePath, @"%@", filePath);
}
参考