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

8

所以我创建了一个自定义抽象类,继承自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
    }

}

如何对这些私有和内部函数进行单元测试?因为我无法从测试文件中访问这些函数。


这个问题的答案在这里解释:https://stackoverflow.com/questions/48208241/testing-a-class-which-preserves-its-state-in-private-variables - Umair Aamir
2个回答

12

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

@testable import MyFramework

似乎我无法使用@testable import MainViewController导入我的自定义类MainViewController它返回No such module 'MainViewController' - Putra
2
如果你正在使用 '@testable import MainViewController',那是不正确的。你需要使用你所测试的框架的名称。通常你的测试项目包含该名称,例如对于一个名为 MyAmazingApp 的工程,它可能是 MyAmazingAppTests。该框架的名称应该是 'MyAmazingApp'。 - totiDev
明白了。谢谢 @totiG - Putra

1
我发现答案是我们不测试私有方法。我们将一个方法设置为私有的是有原因的,它应该被公共方法使用。我认为无论我们是否测试私有方法,最好测试使用私有方法的公共方法。
另外,我在这里找到了一个额外的解释: https://cocoacasts.com/how-to-unit-test-private-methods-in-swift/

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接