Testing private functions in swift

Payal Kandlur
2 min readNov 14, 2023

--

As a developer, considering writing Unit Tests should always be a priority.

Unit test help us know how well is our code written and how well does our code cover all scenarios. This way you can also skip all of those overhead bugs.

Let’s quickly jump into an important question usually asked in interviews, how do you test a private function?

In Swift, Unit Tests are written for functions that are public or internal. Private methods cannot be tested.

Ideally, if a function is declared private it is definitely to make sure that the purpose of this file is nowhere outside the current declaration. The whole point of a private access modifier is to make sure it is not accessible, not even by the Test target. So a straight cut answer would be no, you cannot (and should not😛) test a private function.

But there are scenarios where you want to test a private function. So how do we really test a private function? Well, the approach below is what I personally believe could be a feasible solution.

All that you need to do is have a public method that calls the private method and executes the business logic. And we then test the public function which in turn calls up the private function and executes.

import Foundation

public class Sample {

internal func testInternal() -> String {
return a
}

public func testPublic() -> String {
return b
}

// private function
private func testPrivate() -> String {
return c
}
}

// add a public function to test the private func
extension Sample {
public func publicFuncToTestPrivateFunc() -> String {
return self.testPrivate()
}
}

Now to test this we can follow this:

import XCTest
@testable import TestTests

class TestSample: XCTestCase {

func testExample() {
let sut = Sample()

XCTAssertEqual(a, sut.testInternal())
}

func testPrivateExample() {
let sut = Sample()

XCTAssertEqual(c, sut.publicFuncToTestPrivateFunc())
}
}

This way when the publicFuncToTestPrivateFunc is tested it calls the private function testPrivate.

That’s all!😊 Drop your suggestions and questions if any!

--

--

Responses (3)