Доступ к UIImage внутри цели теста OCUnit - PullRequest
13 голосов
/ 22 декабря 2011

В настоящее время я пишу тест манипуляции изображениями для приложения для iPad.У меня есть папка ресурсов внутри цели моего модульного теста с фотографией внутри, однако, когда я пытаюсь получить к ней доступ, используя [UIImage imageNamed: @ "photo1.jpg"], изображение не возвращается.Если я изменю имя файла на одно в основной папке ресурсов, изображение будет возвращено.

Есть ли способ получить доступ к папке ресурсов внутри цели модульного теста?

Ответы [ 4 ]

23 голосов
/ 23 декабря 2011

Нашел ответ на это, похоже, что вы не можете использовать [UIImage imageNamed:], вы можете получить доступ к изображению, как это:

12 голосов
/ 31 июля 2014

Начиная с iOS 8, у нас есть метод -imageNamed:inBundle:compatibleWithTraitCollection: на UIImage

В Swift:

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

В Objective-C

NSBundle* bundle = [NSBundle bundleForClass:[self class]];
UIImage* image = [UIImage imageNamed:@"imageFileName.extension"
                             inBundle:bundle
        compatibleWithTraitCollection:nil];
3 голосов
/ 07 мая 2014

Сделал для этого удобную категорию.

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
2 голосов
/ 06 декабря 2013

Вы можете использовать следующую категорию (но добавить ее только для проверки цели!). Это заставит UIImage imageNamed: метод работать автоматически в тестовой цели:

.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

.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];
}
...