gpt4 book ai didi

ios - 在 XCTestCase 中使用 UIImage imageNamed

转载 作者:IT王子 更新时间:2023-10-29 08:19:41 24 4
gpt4 key购买 nike

我无法获得 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/

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