Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 445
Anthony Mattox Avatar asked Sep 23 '15 20:09

Anthony Mattox


3 Answers

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.

like image 150
Vick Swift Avatar answered Oct 01 '22 12:10

Vick Swift


Answer provided by https://twitter.com/UINT_MIN

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.

like image 32
Anthony Mattox Avatar answered Oct 01 '22 13:10

Anthony Mattox


@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.

like image 40
jtbandes Avatar answered Oct 01 '22 13:10

jtbandes