调用[NSBundle mainBundle]时XCTest失败

编程入门 行业动态 更新时间:2024-10-24 06:25:56
本文介绍了调用[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.

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

本文发布于:2023-07-16 07:26:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1119333.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:NSBundle   mainBundle   XCTest

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!