如何在Swift中对私有或内部函数进行单元测试?

Zul*_*tra 4 unit-testing nib ios swift

因此,我创建了一个自定义抽象类,该抽象类继承自UIViewController(由RebloodViewController继承)名为MainViewController的类。在这一节课中,我写了一个可重用的笔尖注册函数

class MainViewController: RebloodViewController {

    typealias Cell = RebloodViewController.Constants.Cell

    internal func registerNib(_ cellNib: Cell.Nib, target: UICollectionView) {

        let nib = UINib(nibName: cellNib.rawValue, bundle: nil)

        do {
            let identifier = try getCellIdentifierByNib(cellNib)
            target.register(nib, forCellWithReuseIdentifier: identifier)
        } catch {
            fatalError("Cell identifier not found from given nib")
        }
    }

    private func getCellIdentifierByNib(_ nib: Cell.Nib) throws -> String {

        var identifier: String? = nil

        switch nib {
        case .articles:
            identifier = Cell.Identifier.articles.rawValue
        case .events:
            identifier = Cell.Identifier.events.rawValue
        }

        guard let CellIdentifier = identifier else {
            throw MainError.cellIdentifierNotFound
        }

        return CellIdentifier
    }

}
Run Code Online (Sandbox Code Playgroud)

对这些私有和内部功能进行单元测试的最佳方法是什么?因为我无法从测试文件访问功能。

tot*_*tiG 5

您将无法测试私有功能。但是您可以测试内部的。在测试中,在其中导入框架(例如,导入MyFramework)的地方,将其更改为:

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

  • 如果您使用的是“ @testable import MainViewController”,那是不正确的。您需要使用要测试的框架的名称。通常,您的测试项目包含此名称,对于名为MyAmazingApp的项目,它可能是MyAmazingAppTests。框架名称为“ MyAmazingApp” (2认同)