gpt4 book ai didi

ios - 调用 [NSBundle mainBundle] 时 XCTest 失败

转载 作者:可可西里 更新时间:2023-11-01 06:22:56 25 4
gpt4 key购买 nike

我有一些代码在某些时候调用[NSBundle mainBundle],主要是为了读取/设置首选项。当我对该方法进行单元测试时,测试失败,因为测试的 mainBundle 不包含该文件。

这是 a known issue ,Apple 不会修复,因为他们认为它是 not a bug :

the gist of their reply is that XCTest is working correctly by returning it’s own main bundle instead of the bundle of the test target.

以前我们的代码库在 NSBundle+mainBundle 类方法上使用类别覆盖来解决这个问题。但是this is dangerous because the behaviour of overriding an existing method in a category is undefined .

If the name of a method declared in a category is the same as a method in the original class, or a method in another category on the same class (or even a superclass), the behavior is undefined as to which method implementation is used at runtime.

实际上 Xcode 会警告您:

Category is implementing a method which will also be implemented by its primary class

那么,解决这个问题的正确方法是什么?

最佳答案

解决此问题的最简单和最干净的方法是在单元测试中部分模拟 NSBundle 类以在调用 [NSBundle mainBundle 时返回 [NSBundle bundleForClass:[self class]] ]

你可以把它放在你的 -setup 方法中,这样它就可以为你的整个测试类模拟:

static id _mockNSBundle;

@implementation MyTests

- (void)setUp
{
[super setUp];

_mockNSBundle = [OCMockObject niceMockForClass:[NSBundle class]];
NSBundle *correctMainBundle = [NSBundle bundleForClass:self.class];
[[[[_mockNSBundle stub] classMethod] andReturn:correctMainBundle] mainBundle];
}

@end

干净整洁。

[ Source ]

关于ios - 调用 [NSBundle mainBundle] 时 XCTest 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28993551/

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