gpt4 book ai didi

ios - 在单元测试中断言 UIImage 的最佳方式是什么?

转载 作者:可可西里 更新时间:2023-11-01 04:41:55 25 4
gpt4 key购买 nike

假设我正在为 View Controller 上的 tableView:cellForRowAtIndexPath: 委托(delegate)方法编写单元测试。根据我传入的索引路径,此方法可以返回几个不同的单元格配置。

我可以轻松断言 cell.textLabel.text 属性。但是我如何断言 cell.imageView.image 属性包含正确的图像?图像或 imageView 都没有(公共(public) API)属性,我可以使用它来查找图像名称或文件名。

我想出的最好办法是创建 smallest possible valid .png (使用 [UIImage imageWithData:] 所以我在单元测试中不接触磁盘)并断言我从 cell.imageView.image 获得的字节数组是一个我预计。我创建了一个 OCHamcrest matcher让它变得更好一点,但这是一种不令人满意且不灵活的方法。

有没有人有更好的主意?

最佳答案

如果您使用[UIImage imagedNamed:],图像会被缓存。摘自UIImage class reference对于 imagedNamed::

This method looks in the system caches for an image object with the specified name and returns that object if it exists. If a matching image object is not already in the cache, this method loads the image data from the specified file, caches it, and then returns the resulting object.

这意味着您可以在 cell.imageView.image == [UIImage imagedName:@"my_image"] 上断言,因为这是一个指针比较,并且由于图像被缓存多次调用 imageNamed: 具有相同的名称将返回相同的指针。即使内存变得紧张,您仍然应该没问题,正如 UIImage 类引用所解释的那样:

In low-memory situations, image data may be purged from a UIImage object to free up memory on the system. This purging behavior affects only the image data stored internally by the UIImage object and not the object itself.

关于ios - 在单元测试中断言 UIImage 的最佳方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19299736/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com