39

「iPhone開発ガイド」に合わせてOCUnitテストを作成しました。テストしたいクラスは次のとおりです。

// myClass.h
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface myClass : NSObject {
    UIImage *image;
}
@property (readonly) UIImage *image;
- (id)initWithIndex:(NSUInteger)aIndex;
@end


// myClass.m
#import "myClass.m"

@implementation myClass

@synthesize image;

- (id)init {
    return [self initWithIndex:0];
}

- (id)initWithIndex:(NSUInteger)aIndex {
    if ((self = [super init])) {
        NSString *name = [[NSString alloc] initWithFormat:@"image_%i", aIndex];
        NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"png"];
        image = [[UIImage alloc] initWithContentsOfFile:path];
        if (nil == image) {
            @throw [NSException exceptionWithName:@"imageNotFound"
                reason:[NSString stringWithFormat:@"Image (%@) with path \"%@\" for current index (%i) wasn't found.",
                    [name autorelease], path, aIndex]
                userInfo:nil];
        }
        [name release];
    }
    return self;
}

- (void)dealloc {
    [image release];
    [super dealloc];
}

@end

そして私のユニットテスト(LogicTestsターゲット):

// myLogic.m
#import <SenTestingKit/SenTestingKit.h>
#import <UIKit/UIKit.h>
#import "myClass.h"

@interface myLogic : SenTestCase {
}
- (void)testTemp;
@end

@implementation myLogic

- (void)testTemp {
    STAssertNoThrow([[myClass alloc] initWithIndex:0], "myClass initialization error");
}

@end

必要なすべてのフレームワーク、「myClass.m」および画像がターゲットに追加されました。しかし、ビルド時にエラーが発生します:

[[myClass alloc] initWithIndex:0] raised Image (image_0) with path \"(null)\" for current index (0) wasn't found.. myClass initialization error

このコード(初期化)は、アプリケーション自体(メインターゲット)で正常に機能し、後で正しい画像を表示します。プロジェクトフォルダ(build/Debug-iphonesimulator/LogicTests.octest/)も確認しました。必要な画像ファイルがあります(LogicTestsそのうちの1つです)。Info.plistimage_0.png

どうしたの?

4

1 に答える 1

128

この問題の解決策は 1 つしか見つかりませんでした。

単体テストをビルドすると、メイン バンドルのパスがプロジェクトのバンドル (作成された .app ファイル) と等しくありません。また、LogicTests バンドル (作成されたLogicTests.octestファイル) とは異なります。

単体テスト用のメインバンドルは のようなもの/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.1.3.sdk/Developer/usr/binです。そのため、プログラムは必要なリソースを見つけることができません。

最終的な解決策は、直接バンドルを取得することです。

NSString *path = [[NSBundle bundleForClass:[myClass class]] pathForResource:name ofType:@"png"];

それ以外の

NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"png"];
于 2010-06-21T04:04:40.130 に答える