ios - 在 XCTestCase 中使用 UIImage imageNamed

标签 ios objective-c unit-testing uiimage xctest

我无法获得 Cocoa Touch 静态库的 XCTestCase 单元测试,它依赖于使用 imageNamed 的代码来工作。

我将我的图像“plane.png”添加到测试目标,但是 [UIImage imageNamed] 一直返回 nil。
当我在测试中明确指定图像的路径并从文件加载图像时,它确实有效。

NSString* imagePath = [[[NSBundle bundleForClass:[self class]] resourcePath] stringByAppendingPathComponent:@"plane.png"];
UIImage* imageWorks = [UIImage imageWithContentsOfFile:imagePath];

UIImage* imageStaysNil = [UIImage imageNamed:@"plane.png"];

如何为使用 imageNamed 的代码编写单元测试?

最佳答案

在 XCTest 中,您不在 mainBundle 中。因此,从您的 XCTest 包中获取图像。

(此解决方案适用于 iOS8+)

对象

[UIImage imageNamed:@"..." inBundle:[NSBundle bundleForClass:[self class]] compatibleWithTraitCollection:nil];

swift

UIImage(named: "...", in: Bundle(for: type(of: self)), compatibleWith: nil)

关于ios - 在 XCTestCase 中使用 UIImage imageNamed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22906462/

相关文章:

ios - 框架链接

iPhone - 轮播

java - Junit - 测试不同的类

c# - 使用 Rhino 模拟模拟 ASPNET MVC DependencyResolver

ios - UIViewControllerRepresentable 在 Xcode 14 iOS 16 上崩溃

ios - 警告时 UIAlertController : 0x7ff211650140 called in Swift

ios - 核心数据操作中 100% CPU

unit-testing - 痣和 SharePoint 行为类型

objective-c - ivars 和属性应该在头文件还是实现文件中声明?

ios - Obj-c中iVar和self.iVar的保留计数是多少?