Adding Swift Unit Tests to a Mixed Language Xcode Project


Adding Swift Unit Tests to a Mixed Language Xcode Project

How do you set up unit tests to test Swift classes added to a previously Objective-c only project?
I've added Swift classes to my project and am able to work with them in other Swift and Objective-c files; however, I'm unable to access them from my test classes.
The import statement I believe is correct is @testable import MyAppModuleName which is what is added to the example test class in Xcode's templates. The error produced by that line is Cannot import module being compiled. This error is in Xcode 7 using Swift 2.


Answer 1:

I had similar issues working on a workspace with a mix of Objective-C and Swift code base and wanted to write unit test cases for my Swift files. Below are the steps I took to resolve the issue.

  • I set ‘Enable testability’ to ‘YES’ in project’s Build Settings
  • I also set ‘Defines Module’ to ‘YES’ in my project’s Build Settings.
  • For the regular .swift file(s) within my project, say MyApp, I was
    going to write test cases for, I have both the main “MyApp” and the
    MyAppUnitTests” Targets checked under Target Membership.

I then selected my unit test file(s), declared the ‘@testable import MyApp‘ at the top, beneath the ‘import XCTest‘, and only checked the “MyAppUnitTests” under Target membership.
Cleaned, built and Run and everything worked like charm. Hope this helps.

Answer 2:

Answer provided by

In my case the both targets (the application and the tests) had the same module name in the build settings. Changing the module name of the test target resolved the issue.

Answer 3:

@testable import is for when you’re trying to import code from your main module from your test target.Your test code should not be a member of your app target — you should have a separate test target. See Using Unit Tests for details.