I have the following UIImage
category:
@implementation UIImage (Exception)
+ (nullable UIImage *)imageCanThrowWithData:(NSData *)data error:(NSError **)errorPtr
{
UIImage *image = nil;
@try {
image = [self imageWithData:data];
} @catch (id exception) {
*errorPtr = [NSError errorWithDomain:@"mydomain" code:0 userInfo:nil];
}
return image;
}
@end
And then I am trying to test this with OCMock:
excerpt from setup ...
beforeEach(^{
NSString* labelPath = [[NSBundle mainBundle] pathForResource:@"image" ofType:@"jpg"];
imageData = [NSData dataWithContentsOfFile:labelPath];
image = [UIImage imageWithData:imageData];
});
it(@"should return the image if no exception is thrown", ^{
id mock = OCMStrictClassMock([UIImage class]);
NSError *error = nil;
OCMStub([mock imageWithData:OCMOCK_ANY]).andReturn(image);
OCMStub([mock imageMightThrowWithData:imageData error:&error]).andReturn([UIImage imageMightThrowWithData:imageData error:&error]);
UIImage* resultImage = [[mock expect] imageMightThrowWithData:imageData error:&error];
expect(resultImage).toNot(beNil());
expect(error).to(beNil());
[mock stopMocking];
});
Why is resultImage
is nil
.
Notes:
I am not an expert on OCMock, so I might be doing something naive.
UIImage imageWithData can throw an exception in case you are dealing with core data external storage.