2011-12-22 12 views
12

Actualmente estoy escribiendo una prueba de manipulación de imágenes para una aplicación de iPad. Tengo una carpeta de recursos dentro de mi objetivo de prueba de unidad con una foto adentro, sin embargo, cuando intento acceder usando [UIImage imageNamed: @ "photo1.jpg"] no se devuelve ninguna imagen. Si cambio el nombre del archivo a uno en la carpeta principal de Recursos, se devuelve una imagen.Acceso a un UIImage dentro de un objetivo de prueba OCUnit

¿Hay alguna manera de acceder a la carpeta de Recursos dentro del objetivo de prueba de la unidad?

Respuesta

23

encontrado la respuesta a esto, parece que no se puede utilizar [UIImage imageNamed:], puede acceder a la imagen como esta:

NSBundle *bundle = [NSBundle bundleForClass:[self class]]; 
NSString *imagePath = [bundle pathForResource:@"photo1" ofType:@"jpg"]; 
UIImage *image = [UIImage imageWithContentsOfFile:imagePath]; 
2

Usted puede usar la siguiente categoría (pero sólo para agregarlo objetivo de prueba!). Esto hará que UIImage imageNamed: método de trabajo de forma automática en el destino de la prueba:

archivo .h

/** 
* UIImage imageNamed: method does not work in unit test 
* This category provides workaround that works just like imageNamed method from UIImage class. 
* Works only for png files. If you need other extension, use imageNamed:extension: method. 
* NOTE: Do not load this category or use methods defined in it in targets other than unit tests 
* as it will replace original imageNamed: method from UIImage class! 
*/ 
@interface UIImage (ImageNamedForTests) 

/** 
* Returns image with the specified name and extension. 
* @param imageName Name of the image file. Should not contain extension. 
* NOTE: You do not have to specify '@2x' in the filename for retina files - it is done automatically. 
* @param extension Extension for the image file. Should not contain dot. 
* @return UIImage instance or nil if the image with specified name and extension can not be found. 
*/ 
+ (UIImage *)imageNamed:(NSString *)imageName extension:(NSString *)extension; 


@end 

archivo .m

#import "UIImage+ImageNamedForTests.h" 
#import <objc/runtime.h> 

@implementation UIImage (ImageNamedForTests) 

+ (void)load { 
    [self swizzleClassMethod]; 
} 

+ (void)swizzleClassMethod { 
    SEL originalSelector = @selector(imageNamed:); 
    SEL newSelector = @selector(swizzled_imageNamed:); 
    Method origMethod = class_getClassMethod([UIImage class], originalSelector); 
    Method newMethod = class_getClassMethod([UIImage class], newSelector); 
    Class class = object_getClass([UIImage class]); 
    if (class_addMethod(class, originalSelector, method_getImplementation(newMethod), method_getTypeEncoding(newMethod))) { 
     class_replaceMethod(class, newSelector, method_getImplementation(origMethod), method_getTypeEncoding(origMethod)); 
    } else { 
     method_exchangeImplementations(origMethod, newMethod); 
    } 
} 

+ (UIImage *)swizzled_imageNamed:(NSString *)imageName { 
    return [self imageNamed:imageName extension:@"png"]; 
} 

+ (UIImage *)imageNamed:(NSString *)imageName extension:(NSString *)extension { 
    NSBundle *bundle = [NSBundle bundleForClass:[SomeClassFromUnitTestTarget class]];//Any class from test bundle can be used. NOTE: Do not use UIImage, as it is from different bundle 
    NSString *imagePath = [bundle pathForResource:imageName ofType:extension]; 
    return [UIImage imageWithContentsOfFile:imagePath]; 
} 
3

Hecho una categoría útil para esto.

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

dice así:

@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 
11

Desde iOS 8 tenemos el: Método -imageNamed:inBundle:compatibleWithTraitCollection: en UIImage

En Swift:

let bundle = NSBundle(forClass: self.dynamicType) 
let image:UIImage? = UIImage(named: "imageFileName", 
          inBundle:bundle, 
    compatibleWithTraitCollection:nil) 

En Objective-C

NSBundle* bundle = [NSBundle bundleForClass:[self class]]; 
UIImage* image = [UIImage imageNamed:@"imageFileName.extension" 
          inBundle:bundle 
     compatibleWithTraitCollection:nil]; 
+0

Esta respuesta debería aparecer en la parte superior. Creé un nuevo inicializador para UIImage para hacer exactamente lo que esto hace. Me siento un poco tonto en este momento. https://gist.github.com/Psidium/6d15525d4fba7b191290 –

+0

Gracias, esto resolvió mi problema. –

Cuestiones relacionadas