mfaani
mfaani

Reputation: 36317

What's the difference between importing a target into unit testing and including that file among the target Membership?

When I'm writing tests I can do:

@testable import TestProduct

How is the above different from adding the Test File to a specific Target?

enter image description here

Ultimately my question is: Had I made my unitTests a target to all my files...would it be equivalent to doing:

@testable import TestProduct

If not, then what is the difference?

Upvotes: 24

Views: 6534

Answers (3)

Aaron
Aaron

Reputation: 7145

From the Swift docs under the heading Access Levels for Unit Test Targets (emphasis added)

When you write an app with a unit test target, the code in your app needs to be made available to that module in order to be tested. By default, only entities marked as open or public are accessible to other modules. However, a unit test target can access any internal entity, if you mark the import declaration for a product module with the @testable attribute and compile that product module with testing enabled.

These docs say that the @testable attribute provides your Unit Test target access to all internals of the module marked as @testable. Thus letting you avoid having to manually add individual files in that module to the Unit Test target.

Upvotes: 25

user4527951
user4527951

Reputation:

Target is an end product created by running "build" in Xcode. It might be an app, or a framework, or static library, or a unit test bundle.

So whichever file you add to a particular target it gets built by xcode and gets added to the end product for that target.

So to answer your question if you add the above file to your test target it will be accessible to the files in your test target without importing the module TestProduct and it will get copied to your test bundle product directory

And when you are writing the below line what it does is it simply enable your test target to access the internal files of TestProduct

@testable import TestProduct

So if you add that file to both the targets it will get built twice for each target and will also get copied to respective product directories, which is waste of really not needed.

Upvotes: 2

Ash
Ash

Reputation: 138

Honey. @testable import YourAppModuleName exist in your tests - unit testing. This will expose Any public and default symbols to your tests. private symbols are still unavailable. This is in build settings.

Create a new file in the test target and name it to something like MyFirstSpec.swift. Put this content into it. OR Create a framework target. If you’re not a big fan of duplicating files, you can create a framework target that includes the source files you’re looking to test. Also, you can refer this on github for automation: https://github.com/johnsundell/playground

Upvotes: 0

Related Questions