2012-08-13 72 views
7

我正在为加载图像并进行一些颜色处理的类写一个测试。 图像加载加载单元测试的测试图像

UIImage* image = [UIImage imageNamed:imageName]; 

如果我运行的应用程序,一切都很好,并如预期的图像加载。我添加了一个单元测试,在测试过程中应该使用特定的测试图像加载。如果我运行测试夹具,图像不会被加载。目前我读到的是,imageNamed方法总是从应用程序包的资源文件夹中加载。我怎样才能将其改变为我的测试包?

回答

0

好,其中一个方案是向资源添加到您的测试(应用程序)。

亲自,我只是使用路径(initWithContentsOfFile:),数据(initWithData:)等。这可能涉及引入一些参数 - 但在很多情况下,这是,因为该参数可用于测试更多输入图像文件(如果您喜欢),而不会更改/克隆/重新打包应用程序。

+0

但这意味着你改变用于测试目的的生产代码,这不应该是这样è特别不适用于使您的生活更轻松的框架部件;)。 – trumi 2012-08-14 19:42:59

+0

@truni所以...你试图说服我,你正在使用'[UIImage imageNamed:]'为你的框架的部分,这就是它应该的方式?在这种情况下使用'[UIImage imageNamed:]'是一个非常糟糕的主意,原因有几个。如果你正在编写一个faux-ios框架,请使用NSBundle并指定或找到你的faux-ios框架的资源目录。然后使用除[UIImage imageNamed:]'以外的内容。然后为您的测试变体创建另一个包并运行所有包中的测试。 – justin 2012-08-14 20:08:47

+0

,在这种情况下,它并不会改变测试代码,它会改变你的代码,因为你的代码做错了事情。而不是一直创建新的包,您可以将这些参数传递给您的框架接口(公共或私有)。 – justin 2012-08-14 20:21:58

2

如果你的意思是你有,你想使用只能在测试(即测试夹具)的测试包的形象,去看看this answer

您可以根据这个问题的答案用[NSBundle bundleForClass:[SomeClassThatExistsInTheAppOnly class]]得到实际应用的一个NSBundle。这使您可以专门定位测试包中的应用程序包。

4

这是一个方便的类别。

image = [UIImage testImageNamed:@"image.png"]; 

是这样:

@interface BundleLocator : NSObject 
@end 

@interface UIImage (Test) 
+(UIImage*)testImageNamed:(NSString*) imageName; 
@end 

@implementation BundleLocator 
@end 

@implementation UIImage (Test) 
+(UIImage*)testImageNamed:(NSString*) imageName 
{ 
    NSBundle *bundle = [NSBundle bundleForClass:[BundleLocator class]]; 
    NSString *imagePath = [bundle pathForResource:imageName.stringByDeletingPathExtension ofType:imageName.pathExtension]; 
    return [UIImage imageWithContentsOfFile:imagePath]; 
} 
@end 
1

你也使用这个(斯威夫特):

let bundle = NSBundle(forClass: MyClass.self) 
let img = UIImage(named: "TestImage", inBundle: bundle, compatibleWithTraitCollection: nil) 
4

在雨燕3.0,你会怎么做:

let bundle = Bundle.init(for: NameOfYourTestClass.self) 
let image = UIImage(named: "TestImage", in: bundle, compatibleWith: nil) 

NameOfYourTestClass是你的测试班的名字✌️

0

要改变应用程序包:

设束=软件包(标识符: “org.cocoapods.ACSPLib”)

设相片= UIImage的(命名为:nameofThePhoto,在:束,compatibleWith:无)

束标识符

bundle identifier for pod