2010-06-18 45 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