【问题标题】:OCUnit & NSBundleOCUnit & NSBundle
【发布时间】:2011-03-05 06:23:04
【问题描述】:

我根据“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/) - 有 LogicTestsInfo.plist 和必要的图像文件(image_0.png 就是其中之一)。

怎么了?

【问题讨论】:

标签: unit-testing resources ocunit nsbundle


【解决方案1】:

只找到了一个解决这个问题的方法。

当我构建我的单元测试时,主包的路径不等于我的项目包(创建的 .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"];

【讨论】:

  • 感谢您的回答。也可以使用 [self class],留下这样的一行:NSString *path = [[NSBundle bundleForClass:[self class]] pathForResource:name ofType:@"png"];
  • 据我所知,当您开发标准 iPhone 应用程序时,唯一的捆绑包用于存储您的所有源和资源。因此,理论上,任何“自定义”(由您自己创建)类都可以在这里使用。但我没有检查这个想法。
  • 非常感谢,过去 3 天我一直在寻找这个答案
  • 在为此苦苦挣扎了一段时间后,这个答案真是神来之笔。尽管已有近 6 年的历史,但对于像我这样想要对包含捆绑包的静态库进行单元测试的人来说,它仍然是一个很好的解决方案。
猜你喜欢
  • 1970-01-01
  • 2016-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多