What is @testable?

Samruddhi Jadhav
2 min readOct 28, 2018

--

When we write code we define access level of the classes and the methods as per their usage. While writing tests we have to access these classes and methods in test target.

Almost all entities in code have a default access level of internal if we do not specify an explicit access level. As a result, in many cases we do not need to specify an explicit access level in our code.

The swift’s access control model prevents an external entity from accessing anything declared as internal in an app or framework. By default to be able to access these items from our tests code, we would need to elevate their access level to at least public, reducing the benefits of swift type safety.

Solution:

1. Enable Testability build setting to YES. Xcode includes the -enable-testing flag during compilation. This makes swift entities declared in the complied module eligible for higher level of access.

2. When we add @testable attribute to an import statement for module complied with testing enabled, we activate elevated access for that module in that scope. Classes and class members marked as public behave as if they were marked open. Other entities marked as internal act as if they were declared public.

NOTE:

we don’t change our source code in anyway. We only modify the compilation (by setting the flag).

And the test code (by modifying import statement).

@testable provides access only for internal functions; fileprivate and private declarations are not visible outside of their usual scope when using testable.

Thanks For Reading 🎾

--

--