从Swift测试文件中调用Objective-C类

pra*_*awn 5 unit-testing objective-c swift

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

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

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

我尝试做以下。

@testable import MyModule
Run Code Online (Sandbox Code Playgroud)

但是,这似乎仅在所有文件都在Swift中时才起作用,而对我而言并非如此。

我在项目设置中尝试了其他几项,但是这些似乎都不起作用。

我是否明显遗漏了一些东西?

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.
    }
}
Run Code Online (Sandbox Code Playgroud)

Adn*_*tab 6

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

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

在您的Objective-C桥接头文件中,导入要公开给Swift的每个Objective-C头。例如:

导入“ XYZCustomCell.h”

导入“ XYZCustomView.h”

在“构建设置”的“ Swift编译器-代码生成”中,导入“ XYZCustomViewController.h”,确保“ Objective-C桥接头”

下的build设置具有桥接头文件的路径。该路径应相对于您的项目,类似于在“构建设置”中指定Info.plist路径的方式。在大多数情况下,您无需修改​​此设置。

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

  1. 在Objective-C中使用Swift
  2. 回答另一个堆栈溢出问题
  3. 如何快速使用Objective-C