Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit tests a private or internal function in Swift?

So I created a custom an abstract class who inherit from UIViewController (Inherited by RebloodViewController) class named MainViewController. In this class I write a reusable nib registration function

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
    }

}

What is the best way to unit test these private and internal function? Because I can't access the functions from the test files.

like image 601
Putra Avatar asked Jan 17 '18 08:01

Putra


2 Answers

You will not be able to test the private functions. But you can test internal ones. In your test, where you import your framework, eg import MyFramework, change it to:

@testable import MyFramework
like image 200
totiDev Avatar answered Oct 09 '22 14:10

totiDev


I found the answer is we don't test private methods. We put a method private for a reason and it should be used by a public method. I assume whether we test private method, it's better to test the public method that uses the private method.

Another extra explanation I found it here: https://cocoacasts.com/how-to-unit-test-private-methods-in-swift/

like image 39
Putra Avatar answered Oct 09 '22 15:10

Putra