Run Swift Package tests in release mode in Xcode

Viewed 2344

I am trying to run the test target of a Swift package in Xcode in release mode without generating an Xcode project.

However, when I set the build configuration of the test scheme to release, the build fails because of a missing -enable-testing flag that has to be passed to the compiler when @testable import is used.

How can I add this flag in Xcode for a Swift Package? Note that the traditional build configuration options are not available because no Xcode project exists. Adding -Xswiftc -enable-testing as launch arguments for the test scheme does not work.

2 Answers

You can pass swift compiler flags using the swiftSettings parameter of the target(name:dependencies:path:exclude:sources:publicHeadersPath:cSettings:cxxSettings:swiftSettings:linkerSettings:) function in your SPM manifest file:

import PackageDescription

let package = Package(
    name: "MyPackage",
    targets: [
        .target(name: "MyPackage", swiftSettings: [.unsafeFlags(["-enable-testing"])]),
        .testTarget(name: "MyPackageTests", dependencies: ["MyPackage"]),
    ]
)

If on the other hand you want to run your tests from the terminal you can use -Xswiftc option like normally:

swift test -c release -Xswiftc -enable-testing

You can compile your tests for Release by removing @testable attribute of an import statement:

// MyPackageTests.swift
import XCTest
import MyPackage
...

It's partial solution because your tests don't have access to internal entities in your module but it works great for public ones.

Related