我有以下UIImage
类别:
@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
然后我试图用 OCMock 测试这个:
设置摘录...
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];
});
为什么resultImage
是nil
。注意:
我不是 OCMock 方面的专家,所以我可能会做一些幼稚的事情。
如果您正在处理核心数据外部存储,UIImage imageWithData 可能会引发异常。