7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[mainBundle pathForResource]はTestCaseでは利用できない?

Last updated at Posted at 2014-05-03

あるテキストファイルを読むヘルパークラスの動作確認をするために、たまにはテストでも書くかと、安易な気持ちで書き始めたら詰まってしまった。

端的に述べると、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);
}

参考

7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?