With the exception of the Command Line Tool project type, when you create a new project in Xcode 7, a unit test target is included by default. See specific instructions for a Command Line Tool Project. To write unit tests, you'll need to be able to use your main target's code from within your test target.
In order to test code written in Swift, you'll need to do two things:
- Set "Defines Module" in your
.xcodeprojtoYES.
- To do this in Xcode: Choose your project, then "Build Settings", then "Packaging" header, then "Defines Module" line, then select "Yes". Note: you may have to choose "All" (Build Settings) instead of "Basic" to see the "Packaging" section.
@testable import YourAppModuleNamein your unit tests. This will expose Anypublicandinternal(the default) symbols to your tests.privatesymbols are still unavailable.
// MyAppTests.swift
import XCTest
@testable import MyModule
class MyClassTests: XCTestCase {
// ...
}Quick integration in the Xcode Test Navigator suffers from some limitations (open issue). Quick tests will not show up in the navigator until they've been run, repeat runs tend to reset the list in unpredictable ways and the tests cannot be run from the gutter next to the source code. Please file a radar to Apple and mention this as a duplicate to rdar://26152293 to promote this feature request for Apple Engineers.
Some developers advocate adding Swift source files to your test target. However, this leads to subtle, hard-to-diagnose errors, and is not recommended.
- Add a bridging header to your test target.
- In the bridging header, import the file containing the code you'd like to test.
// MyAppTests-BridgingHeader.h
#import "MyClass.h"You can now use the code from MyClass.h in your Swift test files.
- Bridge Swift classes and functions you'd like to test to Objective-C by
using the
@objcattribute. - Import your module's Swift headers in your unit tests.
@import XCTest;
#import "MyModule-Swift.h"
@interface MyClassTests: XCTestCase
// ...
@endImport the file defining the code you'd like to test from within your test target:
// MyAppTests.m
@import XCTest;
#import "MyClass.h"
@interface MyClassTests: XCTestCase
// ...
@end- Add a target to your project in the project pane.
- Select "OS X Unit Testing Bundle".
- Edit the scheme of your main target.
- Select the "Test" node, click the "+" under the "Info" heading, and select your testing bundle.