调用[NSBundle mainBundle]时XCTest失败 [英] XCTest fails when calling [NSBundle mainBundle]

查看:105
本文介绍了调用[NSBundle mainBundle]时XCTest失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have some code that calls [NSBundle mainBundle] at some point, mainly to read/set preferences. When I unit test the method, the test fails because the test's mainBundle does not contain the file.

这是一个已知的问题,Apple将不会修复,因为他们认为它是不是错误

This is a known issue, that Apple won't fix as they consider it is not a bug:


他们回复的要点是XCTest正常工作返回它自己的主包而不是测试目标的包。

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.

以前我们的代码库在<$ c $上使用类别覆盖c> NSBundle 的 + mainBundle 类方法来解决这个问题。但这很危险,因为覆盖类别中的现有方法是未定义的

Previously our codebase was using a category override on NSBundle's +mainBundle class method to work around this. But 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警告关于它:

Actually Xcode warns you about it:


类别实现的方法也将由其主要类实现

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

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

So, what is the proper method to address the issue?

推荐答案

解决此问题的最简单,最简洁的方法是在单元测试中部分模拟NSBundle类以返回<$ c当你打电话给 [NSBundle mainBundle] 时,$ c> [NSBundle bundleForClass:[self class]] 。

The simplest and cleanest way of fixing this issue is to partially mock the NSBundle class in your unit tests to return [NSBundle bundleForClass:[self class]] when you call [NSBundle mainBundle].

您可以将它放在 -setup 方法中,以便为整个测试类进行模拟:

You may put this in your -setup method so that it is mocked for your entire test class:

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

干净整洁。

[来源 ]

这篇关于调用[NSBundle mainBundle]时XCTest失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆