gpt4 book ai didi

ios - XCTest 的@testable 幕后发生了什么?

转载 作者:搜寻专家 更新时间:2023-10-30 22:03:55 26 4
gpt4 key购买 nike

我知道

@testable import MyModule

提供从“测试”(使用“testTarget”构建)模块 MyModuleTests 探索 MyModule 的非公共(public)成员的能力。

我的“非测试”模块需要相同的功能。不在生产中,只是在 Debug模式下。

我的问题是:你知道怎么做吗?

相关的(我认为,更难的问题):@testable 背后究竟发生了什么魔法?

最佳答案

要回答您的问题,出于调试目的,您实际上可以使用它。假设您有一个工作区 MyAwesomeWkspace 和一个位于 MyAwesomeProject 中的项目。

现在,创建一个名为 MyAwesomeModule 的新 framework 也称为 module。在该模块中创建一个名为 Person 的非公共(public)类。

如果您尝试通过执行 import MyAwesomeModule 然后像 let p = Person( ) 你会遇到一个错误。

但是如果您执行 @testable import MyAwesomeModule,奇迹就会发生,您现在可以使用该类了。

基本上 @testable 允许您测试您没有声明为公开的内容。如您所见,注释仅适用于 import here .

所以为了工作,目标是用-enable-testing编译的,这样你就可以访问非公共(public)成员。至少基于什么是here

因为默认情况下,debug 构建配置是使用 -enable-testing 编译的,我向您展示的示例将起作用。但是,如果您将构建配置更改为 release,您将看到一条错误消息,提示 Module .. was not compiled for testing since the release 配置不是用标志 build 的。

The Swift access control model, as described in the Access Control section of The Swift Programming Language (Swift 4), prevents an external entity from accessing anything declared as internal in an app or framework. By default, to be able to access these items from your test code, you would need to elevate their access level to at least public, reducing the benefits of Swift’s type safety.

Xcode provides a two-part solution to this problem:

When you set the Enable Testability build setting to Yes, which is true by default for test builds in new projects, Xcode includes the -enable-testing flag during compilation. This makes the Swift entities declared in the compiled module eligible for a higher level of access. When you add the @testable attribute to an import statement for a module compiled with testing enabled, you activate the elevated access for that module in that scope. Classes and class members marked as internal or public behave as if they were marked open. Other entities marked as internal act as if they were declared public.

更多here

后期编辑:swift 的一个很酷的部分是它是开源的。因此,如果您想深入了解“魔法”,请查看:https://github.com/apple/swift

关于ios - XCTest 的@testable 幕后发生了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46798225/

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