How To Link XCTest Dependency To Production / Main Target? - swift

I am trying to write an extension for the XCTest framework in Swift. In order to do so, I created a project with two targets: the main/production target and a test target.
As I am writing an extension for XCTest, I need to import XCTest within my main/production target as well. However, I am having trouble to do so. When in Xcode and I click on my project, then select the main target, go to Build Phases, Link Binary With Libraries and add XCTest there, I get a compile error:
ld: framework not found XCTest
clang: error: linker command failed with exit code 1 (use -v to see invocation)
I also tried the solution provided here which unfortunately doesn't work either.

Auxiliary information on XCTest itself is sparse and hard to find, I was also chasing down the same functionality and finally managed to get it working.
I am on XCode 10.1 and running on a real iPhone with iOS 11. I am certain the general technique will work for other versions, but probably will require a few tweaks.
The general steps are described in this stackoverflow answer, but required several additional steps and tweaks to work for me on a real iPhone:
Is it possible to run XCTest tests in an iOS app?
Follow the steps in the above link. The below steps are deviations from those instructions that were required for me.
Copy in the XCTest framework as described in the above link. NOTE: Use the framework for the iPhone.OS platform and not the simulator as it describes. You can find this framework file inside the actual XCode Application package on your mac. (Right click, "Show Package Contents", then look in ./Contents/Developer/Platforms/iPhoneOS.platform
Disable bitcode in your app target. This solves a linker error. Here is an example of enabling it: how to ENABLE_BITCODE in xcode 7?
When dragging the XCTest.framework file to the linked binaries in your target, ensure that you also drag it to the "Embedded Binaries" which is directly above the "Linked Frameworks and Libraries" option. If you don't do this you will get a runtime error.
The ViewController code to start the tests is slightly different in new Swift, here is what I am using:
import UIKit
import XCTest
class ViewController: UIViewController {
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
print("running tests!")
let suite = XCTestSuite.default;
for test in suite.tests {
test.run()
}
}
}
That should be it! When I run the above app, then touch the screen, all of the tests from my UITesting target run flawlessly and pass!

Related

Mac: Bundle not found in embedded Helper app

I have a Swift Package with shared code.
With Xcode's SPM added to my Xcode project.
Works great in the main app.
Doesn't work in the helper app when exported. Running the helper app in Xcode itself works fine. But when running as an exported and signed app it doesn't work.
This error message was found in console:
Fatal error: unable to find bundle named MySwiftPackageName: file MySwiftPackageName/resource_bundle_accessor.swift, line 27
I double checked, the package is really added at
Build Phase -> Link Binary With Libraries
When I inspect the exported main app and helper app I found the package in the main resources folder but not in the helper app resources folder.
How can I fix this?
In the Swift Package Manager the use of Bundle changes a bit, when you compile the source or open up Xcode a autogenerated code is available to you, which is Bundle.module.
The Bundle.module code is fairly simple and should resolve the issue, it is used like this.
SwiftUI
Image("ImageName", bundle: Bundle.module)
UIKit
UIImage(named: "ImageName", in: .module, with: nil)

Swift PaperOnboarding Module Import Error

I am sorry for such simple question, but I've searched everywhere and read through the paper-onboarding documentation but still can't find a solution to this problem.
I am building a simple iOS app project using the paper-onboarding library, by following this YT tutorial. I keep receiving the error: No such module 'PaperOnboarding'
import UIKit
import PaperOnboarding // <<<ERROR HERE>>>
class OnboardingView: PaperOnboarding {
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
}
I'm not sure how to solve this, could someone shed some light on this?
Xcode: Version 9.3
Cocoapod: Version 1.4.0
Paper-onboarding: Version 4.0.2
This error has nothing to do with the library. It's definitely an error on your part or on the configuration of your project.
How are you adding the library to your project?
If you're adding using CocaPods:
Make sure you do pod install or pod update
After that always open the .xcworkspace file in your project and not the .xcodeproj
If you are opening the correct file:
Check the POD project and the target for the pod you added and in the build settings, make sure Swift Version matches your project version.
Clean your project and run
Close and re-open XCode
but it could be several other things. But make sure all the configuration is correct.
Some Pods require you to use the use frameworks! statement in the Podfile.

Swift 3 Unit Testing - Linker fails when using import #testable

I'm currently trying to write unit tests (NOT UI Tests) for my (macOS) Xcode project. I have created a new Unit Test target which creates a blank unit test file for me.
This complies and links fine, but there are no tests.
As soon as I add the line #testable import Pilot, where Pilot is the name of my App Target, and I try to compile and run, it fails with this message:
Linker command failed with exit code 1 (use -v to see invocation)
I've tried everything I can find, but nothing seems to be working. The other posts I have read on here deal with this problem in UI Tests, but that is because you cannot use #testable in UI Tests. You are supposed to be able to use it in Unit Tests, but I can't figure out why this is not working.
Does anyone have any insight?
If it helps, my project is located at: https://github.com/RohanNagar/pilot-osx
Here is the full PilotTests.swift file:
import XCTest
#testable import Pilot
class PilotTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
If your CocoaPods frameworks not included in the Test targets. It will throw this error.
I made sure running a pod install, but still it failed.
So 'pod deintegrate Yourproject.xcodeproj' and reinstall (pod install), clears the issue.
The import fails because the project fails to link together. I downloaded it and I get the following error trying to run it:
Showing Recent Issues
ld: framework not found Realm for architecture x86_64
Try to clean your build folder, or download the project to a new folder, and fix this issue... after that you'll be able to compile and #testable import Pilot.
Set Host Application to your Project Target.
Also, check the Allow testing Host Application APIs is turned on.
Select your test target
Select Build Phases
In the Framework Search Paths, add this
"${PODS_CONFIGURATION_BUILD_DIR}/" with recursive option

"Module was not compiled for testing" error when using Swift Package Manager

I created a Swift library with swift package init --type library and generated an Xcode project with swift package generate-xcodeproj.
Now I'm trying to run the Test scheme in Xcode. It prints following error:
Module '<title>' was not compiled for testing
However when I run swift build and swift test in terminal, it works fine.
I have ENABLE_TESTABILITY set to YES in all of the targets. I didn't change anything in the project except this. How can I make Xcode perform unit testing?
You need to set the "Enable Testability" to Yes in build setting over your "Main Target"
I was having this issue today, it seems like #testable cannot be used with projects generated by Swift Package Manager.
Removing #testable from my import statements solved this issue. Of course, this means we can only test the public interface of our modules.
Xcode -> Product -> Scheme -> Edit Scheme
Select the Info tab.
Set the following -
Build Configuration: Debug
Add a check mark to Debug executable
Tested with Xcode 12.4(12D4e) and iOS 14.1 deployment target.

MacOS Swift Framework testing fail

I have a framework written in obj-c and swift.
Now i try to run a related unit test target, but I get this error:
2014-07-10 07:45:54.064 xctest[4908:303] The test bundle at /Users/steve/Temporary/Build/Products/Debug/SOGraphDB-Mac Tests.xctest could not be loaded because an unanticipated error occurred: Error Domain=NSCocoaErrorDomain Code=3587 "The bundle “SOGraphDB-Mac Tests” couldn’t be loaded because it is damaged or missing necessary resources." (dlopen_preflight(/Users/steve/Temporary/Build/Products/Debug/SOGraphDB-Mac Tests.xctest/Contents/MacOS/SOGraphDB-Mac Tests): Library not loaded: #rpath/libswiftAppKit.dylib
Referenced from: /Users/steve/Temporary/Build/Products/Debug/SOGraphDB.framework/Versions/A/SOGraphDB
Reason: image not found) UserInfo=0x10011c640 {NSLocalizedFailureReason=The bundle is damaged or missing necessary resources., NSLocalizedRecoverySuggestion=Try reinstalling the bundle., NSFilePath=/Users/steve/Temporary/Build/Products/Debug/SOGraphDB-Mac Tests.xctest/Contents/MacOS/SOGraphDB-Mac Tests, NSDebugDescription=dlopen_preflight(/Users/steve/Temporary/Build/Products/Debug/SOGraphDB-Mac Tests.xctest/Contents/MacOS/SOGraphDB-Mac Tests): Library not loaded: #rpath/libswiftAppKit.dylib
Referenced from: /Users/steve/Temporary/Build/Products/Debug/SOGraphDB.framework/Versions/A/SOGraphDB
Reason: image not found, NSBundlePath=/Users/steve/Temporary/Build/Products/Debug/SOGraphDB-Mac Tests.xctest, NSLocalizedDescription=The bundle “SOGraphDB-Mac Tests” couldn’t be loaded because it is damaged or missing necessary resources.}
Any idea what the root cause can be?
The error seems realated to "Library not loaded: #rpath/libswiftAppKit.dylib"
Both (framework and test bundle) compile without any error or warning (in Beta2)
I had a similar problem, though mine was an iOS test target, linking to a Swift framework, that failed to run on Xcode 6 GM. The test target had run successfully on an early beta of Xcode 6, but the final version reported the runtime error: Library not loaded: #rpath/libswiftCore.dylib
I noticed that a newer project did not have the failure, so I compared the build settings and test code. I was able to resolve the problem with three steps:
The test target needs the "Embedded Target Contains Swift Code" setting to be YES. This tells the linker to add the Swift runtime libraries to the executable.
The test target needs an explicit value for the "Runpath Search Paths" build setting. This tells the loader where to find the Swift runtime libaries. I copied the following setting from a fresh new test target:
LD_RUNPATH_SEARCH_PATHS = $(inherited) #executable_path/../Frameworks #loader_path/../Frameworks
The test cases need to explicitly import any modules that are used by the linked framework. In my project, the framework used UIKit but the test cases only used my framework. When I added an explicit import UIKit to the test cases, the link problem went away.
Since I keep running into this issue whenever I mess with build settings, here's the cleanest answer I can provide as of Xcode 8b5:
If unit tests don't run on iOS, make sure you have:
Runpath Search Paths: #loader_path/Frameworks
If unit tests don't run on macOS, make sure you have:
Runpath Search Paths: #loader_path/../Frameworks
This will show up as LD_RUNPATH_SEARCH_PATHS in your pbxproj file. You can also add $(inherited) to make sure project-wide paths are added as well, but those are probably empty.
Lastly, I didn't need the executable_path/... settings, doesn't make a difference for me whether they're there or not for unit tests.
I had the same problem.
Ended up copying libswiftAppKit.dylib out of the Xcode application directory (I am using beta 3), into a directory that I could reference (not part of an application bundle), then adding the library to the "Link binary with libraries" setting for the test bundle. My tests then started working.
FYI, the path for the dylib was at '/Applications/Xcode6-Beta3.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/libswiftAppKit.dylib'
Probably not a good final solution, but it works for the interim.
My solution was to add a single file to my test target, AppKitTests.swift (or AppKitSpec.swift in my case), and all the file contains is:
// While I don't know why, The.framework is built linked to libswiftAppKit.
// Frameworks do not embed the Swift libraries themselves, it's up to the host
// app to include the necessary libraries. So here we are, including AppKit on
// behalf of The.framework so that the tests can run.
import AppKit
Oh, I also added AppKit to the test target's set of frameworks.
I had this occur to me in Beta 4 and it turned out that I had done it to myself without realizing it.
I had a Framework project called Fnord. My FnordTests target contained a couple of unit test classes that had import Fnord at the top of each file. For some reason Xcode was complaining about those imports and so I commented them out. This is when I started getting the same symptoms while trying to run my unit tests.
I noticed that the settings for my FnordTests target were such that the target would be linked with Fnord.framework, and I realized that it might not be able to do that with the aforementioned import Fnord statements diked-out.
So I put them back in, and everything went back to normal. Curiously, Xcode no longer showed those import statements as being problematic, but this is beta so I can forgive that.
I hope this helps someone.
I ran into the same issue, adding
import AppKit
in the Swift file fixed it