从 Swift 测试文件中调用 Objective-C 类 [英] Call an Objective-C class from a Swift test file

查看:34
本文介绍了从 Swift 测试文件中调用 Objective-C 类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实施单元测试.原始项目是用 Objective-C 编写的.

I'm working on implementing unit tests. The original project was written in Objective-C.

我创建了一个用 Swift 编写的新测试目标.

I created a new Test Target that is written in Swift.

如何在我的测试文件中调用实际应用的 Objective-C 类?

How do I call an Objective-C class of the actual app in my test file?

我已尝试执行以下操作.

I've tried doing the following.

@testable import MyModule

然而,这似乎只有在所有文件都在 Swift 中时才有效,而我的情况并非如此.

However, this seems to only work if all the files are in Swift, which is not the case for me.

我已经尝试了其他一些项目设置,但是,这些似乎都不起作用.

I've tried several other things with the project settings however, none of these seemed to work.

我是否遗漏了一些显而易见的东西?

Am I missing something blatantly obvious?

class MyTests: XCTestCase {

    override func setUp() {
        super.setUp()
        // Put setup code here. This method is called before the invocation of each test method in the class.
    }

    override func tearDown() {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
        super.tearDown()
    }

    func testExample() {
        let vc = HomeViewController() //this line is failing. How do I expose this view controller written in objective c?
        // This is an example of a functional test case.
        // Use XCTAssert and related functions to verify your tests produce the correct results.
    }
}

推荐答案

您需要创建桥接头并将 Objective-C 文件添加到其中.创建一个桥接头YourProductName-Bridging-Header.h,然后在桥接头中import HomeViewController.

You need to create bridging header and add Objective-C file in to that. Create a bridging header YourProductName-Bridging-Header.h and then import HomeViewController in bridging header.

将 Objective-C 代码从同一目标导入 Swift

To import Objective-C code into Swift from the same target

在你的 Objective-C 桥接头文件中,导入每个 Objective-C您想要向 Swift 公开的标头.例如:

In your Objective-C bridging header file, import every Objective-C header you want to expose to Swift. For example:

#import "XYZCustomCell.h"
#import "XYZCustomView.h"
#import "XYZCustomViewController.h" 

在 Build Settings 中,在 Swift Compiler - Code Generation 中,确保 Objective-C Bridging Header下的构建设置有一个桥接头文件的路径.路径应该是相对于你的项目,类似于你的 Info.plist路径在构建设置中指定.在大多数情况下,您不应该需要修改此设置.

In Build Settings, in Swift Compiler - Code Generation, make sure the Objective-C Bridging Header build setting under has a path to the bridging header file. The path should be relative to your project, similar to the way your Info.plist path is specified in Build Settings. In most cases, you should not need to modify this setting.

以下是一些可以帮助您的资源

Below are some resources which can help you

  1. 将 Swift 与 Objective-C 结合使用
  2. 另一个堆栈溢出问题的答案
  3. 如何快速使用 Objective-C

这篇关于从 Swift 测试文件中调用 Objective-C 类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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