I am trying to setup Unit Testing for my project. It is an existing Objective-C app, that I have recently added one Swift class to. I have setup the \'MyProject-Swift.h\' an
I had a similar issue to yours, I think; here was my setup.
I had an object defined in Swift:
// file Foo.swift
@objc public class Foo {
// ...
}
This class was then used in the initializer of an Objective-C object:
// file Bar.h
#import "MyProject-Swift.h"
@interface Bar: NSObject
- (instancetype)initWithFoo:(Foo *)foo;
@end
This made my unit tests for Bar
not compile, since the MyProject-Swift.h
header isn't real and the unit test target can't see it. The release note shared by @hyouuu is on point - but I'm not testing a Swift class, I'm testing an Objective-C class!
I was able to fix this by changing the header file for Bar
to use a forward class reference instead:
// file Bar.h
@class Foo;
@interface Bar: NSObject
- (instancetype)initWithFoo:(Foo *)foo;
@end
I then included MyProject-Swift.h
in Bar.m
, and everything worked - my tests of Objective-C objects written in Objective-C compiled properly and continued running, and I could write new tests for Swift objects in Swift.
Hope this helps!
Thanks to @gagarwal for figuring this out. In our case the product name has a space, which is collapsed in $PROJECT_NAME
, so I had to hard code it. Additionally, by using $CONFIGURATION_TEMP_DIR
instead of $TARGET_TEMP_DIR
, you can remove the parent directory (../
) from the path. So the solution is to add the following to the Header Search Paths in your test target:
"$(CONFIGURATION_TEMP_DIR)/Product Name With Spaces.build/DerivedSources"
Or, if your product does not contain spaces:
"$(CONFIGURATION_TEMP_DIR)/$(PROJECT_NAME).build/DerivedSources"
mySwiftClassTests
(and any other swift classes you want to use in objective-c) needs to be marked @objc
:
@objc class MySwiftClassTests: XCTestCase
Saw in the Xcode 6.1 release note, that this is a known issue... sign... Search for "-swift.h" in the release note https://developer.apple.com/library/content/documentation/Xcode/Conceptual/RN-Xcode-Archive/Chapters/xc6_release_notes.html
Tests written in Objective-C cannot import the Swift generated interfaces header ($(PRODUCT_MODULE_NAME)-Swift.h) for application targets, and therefore cannot be used to test code that requires this header.
Tests for Swift code should be written in Swift. Tests written in Objective-C for framework targets can access the Swift generated interfaces by importing the framework module using @import FrameworkName;. (16931027)
Please see @gagarwal's workaround below which WORKS!