本文介绍了调用[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:

以前我们的代码库在<$ 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.

实际上Xcode警告关于它:

Actually Xcode warns you about it:

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

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失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 00:19