Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Swift files to test target not fixing unit tests

Tags:

I have looked at a lot of blogs and tried many things to get my Swift unit tests to work in Xcode 6.0.1 (or 6.1 for that matter). I'm trying to access classes in my app's target so I wrote this line:

var vc: LoginViewController! 

Of course, I get the "Use of undeclared type 'LoginViewController'" error.

I then try to add LoginViewController to my test target, but then I get "use of unresolved identifier" errors on other classes in my project. So I try to add those classes to my test target, but I end up with a seemingly endless source of errors like the screenshot below:

xcode swift errors

Declaring all my classes as public, causes other errors and seems like bad practice. Is there anyway to include unit tests in a Swift project that relies on many frameworks and classes? I simply want to start with something almost exactly like the code in this article.

like image 505
tfrank377 Avatar asked Oct 31 '14 20:10

tfrank377


2 Answers

After much headache and putting this on the back burner, I found that the main problem was when adding files to the test target membership, the Objective-C classes would still complain. I figured it was an old compatibility issue with the new way Swift does unit tests, but the solution was my test target didn't know there was a bridging header. Thus, I added a reference to it in my test target's build settings, like so:

test target bridging header

It seems simple and obvious now, but the errors were unhelpful. No other solutions I saw for Swift unit tests suggested this could be an issue, but now I know.

Tl;dr

For unit tests to work in Swift, the test target must know everything the app target knows, so add a reference to your bridging header in your test target too (if applicable).

like image 78
tfrank377 Avatar answered Oct 14 '22 13:10

tfrank377


If you're using Xcode 7, there's now a much better way of dealing with this using @testable import {ModuleName}.

Just make sure that the module you want to test has the build setting Enable Testability set to YES.

like image 23
hwaxxer Avatar answered Oct 14 '22 14:10

hwaxxer