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

标签 objective-c swift unit-testing

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

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

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

我已尝试执行以下操作。

@testable import MyModule

但是,这似乎只有在所有文件都在 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.
    }
}

最佳答案

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

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

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" 

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.

下面是一些可以帮助你的资源

  1. Using Swift with Objective-C
  2. Answer to another stack overflow qustion
  3. How to use Objective-C in swift

关于objective-c - 从 Swift 测试文件调用 Objective-C 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39086669/

相关文章:

ios - 在 Swift 中动画绘制圆圈的奇怪问题

angular - 如何以 Angular 对取消订阅功能进行单元测试

ios - 没有用于分配给属性的 setter 方法

ios - 更改 UIScrollView 中的页数

swift - 🫥 Swift isEmoji isEmojiPresentation

android - 同时编写调试和生产代码的最佳做法是什么?

javascript - 有没有办法让 Chai 处理异步 Mocha 测试?

java - 为 DAO 编写测试

ios - 如何确定从外部didSelectRowAtIndexPath(Objective-C)在UITableView中选择了哪些行

ios - 开始导航后无法移动 map