代码之家  ›  专栏  ›  技术社区  ›  kpower

眼束(&N)

  •  38
  • kpower  · 技术社区  · 15 年前

    // 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”和图像都添加到target中。但我有一个错误:

    [[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 Info.plist 以及必要的图像文件( image_0.png 是其中之一)。

    发生了什么?

    1 回复  |  直到 15 年前
        1
  •  128
  •   kpower    15 年前

    当我构建单元测试时,主包的路径不等于我的项目包(创建的.app文件)。而且,它不等于LogicTests bundle(创建的) 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"];