gpt4 book ai didi

unit-testing - OCUnit 和 NSBundle

转载 作者:行者123 更新时间:2023-12-03 07:28:52 24 4
gpt4 key购买 nike

我根据“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] 未找到当前索引 (0) 的路径为\"(null)\"的图像 (image_0)。myClass 初始化错误

此代码(初始化)在应用程序本身(主要目标)中运行良好,稍后显示正确的图像。我还检查了我的项目文件夹(build/Debug-iphonesimulator/LogicTests.octest/) - 有 LogicTestsInfo.plist 和必要的图像文件(image_0.png 就是其中之一)。

出了什么问题?

最佳答案

此问题仅找到一种解决方案。

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

关于unit-testing - OCUnit 和 NSBundle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3067015/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com