【问题标题】:mocking UIImagePNGRepresentation模拟 UIImagePNGRepresentation
【发布时间】:2016-02-26 21:08:05
【问题描述】:

我正在尝试使用 OCMock 模拟 UIImagePNGRepresentation。 UIImagePNGRepresentation 接受 UIImage 并返回 NSData。

但是好像不能把它当作普通函数来模拟。

我尝试了以下,但它没有编译。

id mockAlbumArt = [OCMockObject niceMockForClass:[UIImage class]];
id mockImageData = [OCMockObject niceMockForClass:[NSData class]];

id uiimageMock = [OCMockObject niceMockForClass:[UIImage class]];
[[[uiimageMock expect] andReturn:mockImageData] UIImagePNGRepresentation:mockAlbumArt];

如果您查看 UIImage 的标头,则 UIImagePNGRepresentation 定义为:

UIKIT_EXTERN  NSData * __nullable UIImagePNGRepresentation(UIImage * __nonnull image);                               // return image as PNG. May return nil if image has no CGImageRef or invalid bitmap format

以前有没有人模拟过这个函数?任何帮助将不胜感激,谢谢。

【问题讨论】:

    标签: ios objective-c unit-testing uiimage ocmock


    【解决方案1】:

    你说得对,普通函数不能这样模拟。

    像 OCMock 和 OCMockito 这样的模拟库提供了一种存根和验证方法调用的方法。 UIImagePNGRepresentation 不是一个方法,它是一个独立的 C 函数。

    那么如何替换它进行测试呢?不要直接调用它,而是通过函数指针调用它。对于正常使用,将 UIImagePNGRepresentation 分配给您的指针。为了测试,分配一个你定义的函数。

    【讨论】:

    • 有道理。谢谢。
    【解决方案2】:

    使用 Facebook 库 fishhook 可以轻松实现与此类似的模拟 C 函数。 https://github.com/facebook/fishhook

    在测试文件中写一个替代方法:

    NSData * __nullable swizzled_UIImagePNGRepresentation(UIImage * __nonnull image)
    {
        return [NSData data];
    }
    

    然后从测试函数中我们重新绑定符号,以便调用我们的方法而不是原始方法。有点像混搭的方法。

    -(void)testAlbumArt
    {
         rebind_symbols((struct rebinding[1]){{"UIImagePNGRepresentation", swizzled_UIImagePNGRepresentation}}, 1); 
        ....continue and expect [NSData data] when you call UIImagePNGRepresentation...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-05
      • 2014-10-08
      • 2015-05-04
      • 2012-08-05
      • 1970-01-01
      • 2013-03-09
      • 2011-05-10
      • 1970-01-01
      相关资源
      最近更新 更多