2010-06-18 42 views
38

我创建了与“iPhone开发指南”一致的OCUnit测试。下面是测试我希望类:OCUnit&NSBundle

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

怎么了?

+2

大厦关闭kpower的解决方案,我想出了下面的[Xcode中:TEST VS DEBUG预处理宏] (http://stackoverflow.com/questions/6748087/xcode-test-vs-debug-preprocessor-macros/6763597#6763597)。 – ma11hew28 2011-07-20 14:37:53

回答

127

找到这个问题只有一个解决方案。

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

感谢您的回答。使用[self class]也是可能的,留下如下行:'NSString * path = [[NSBundle bundleForClass:[self class]] pathForResource:name ofType:@“png”];' – Macarse 2011-09-15 14:21:41

+1

据我所知,当您开发标准的iPhone应用程序,唯一的软件包用于存储您的所有来源和资源。所以,从理论上讲,任何“自定义”(自己创建的)类都可以在这里使用。但我没有检查这个想法。 – kpower 2011-09-16 02:35:28

+0

非常感谢,我一直在寻找这个答案在过去3天 – aryaxt 2011-11-03 16:43:04