【问题标题】:How to unit tests a private or internal function in Swift?如何在 Swift 中对私有或内部函数进行单元测试?
【发布时间】:2018-01-17 08:25:44
【问题描述】:

所以我创建了一个自定义的抽象类,它继承自 UIViewController(由 RebloodViewController 继承)名为 MainViewController 的类。在这个类中我写了一个可重用的 nib 注册函数

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
    }

}

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

【问题讨论】:

标签: ios swift unit-testing nib


【解决方案1】:

您将无法测试私有函数。但是你可以测试内部的。在您的测试中,您导入框架的位置,例如导入 MyFramework,将其更改为:

@testable import MyFramework

【讨论】:

  • 似乎我无法使用@testable import MainViewController 导入我的自定义类MainViewController 它返回No such module 'MainViewController'
  • 如果您使用的是“@testable import MainViewController”,那么这是不正确的。您需要使用您正在测试的框架的名称。通常您的测试项目包含这个名称,它可能是 MyAmazingAppTests,用于名为 MyAmazingApp 的项目。框架名称将是“MyAmazingApp”
  • 知道了。谢谢@totiG
【解决方案2】:

我发现答案是我们不测试私有方法。我们将一个方法设为私有是有原因的,它应该由公共方法使用。我假设我们是否测试私有方法,最好测试使用私有方法的公共方法。

我在这里找到了另一个额外的解释: https://cocoacasts.com/how-to-unit-test-private-methods-in-swift/

【讨论】:

    猜你喜欢
    • 2019-09-27
    • 1970-01-01
    • 1970-01-01
    • 2011-07-26
    • 1970-01-01
    • 2018-12-03
    • 2013-02-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多