Search code examples
swiftxcodeswift-package-manager

Sharing code across test targets when using the Swift Package Manager


I have some code that I need to share across test targets, while I'm using the Swift Package Manager. To do this, I have a .testTarget that I also name as a dependency in another .testTarget.

Here is a simple example:

// swift-tools-version:5.3
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
    name: "ExampleLib",
    products: [
        // Products define the executables and libraries a package produces, and make them visible to other packages.
        .library(
            name: "ExampleLib",
            targets: ["ExampleLib"]),
    ],
    dependencies: [
        // Dependencies declare other packages that this package depends on.
        // .package(url: /* package url */, from: "1.0.0"),
    ],
    targets: [
        // Targets are the basic building blocks of a package. A target can define a module or a test suite.
        // Targets can depend on other targets in this package, and on products in packages this package depends on.
        .target(
            name: "ExampleLib",
            dependencies: []),
        .testTarget(
            name: "Common",
            dependencies: ["ExampleLib"]),
        .testTarget(
            name: "ExampleLibTests",
            dependencies: ["Common"]),
            
    ]
)

If I try to build this package in Xcode, I get the following error:

Unable to resolve build file: XCBCore.BuildFile (The workspace has a reference to a missing target with GUID 'PACKAGE-TARGET:Common')

However, if I build from the command line (swift build) or test from the command line (swift test), I get success.

I'm using Xcode 12 beta 6, but have also tried Xcode 11.5 (with a change to the Package.swift header) and get the same results.

Here is the complete Swift package example: https://www.dropbox.com/s/h6ypvbfonnb2zyk/ExampleLib.zip?dl=0

I really would like to use this in Xcode to build for iOS. Thoughts?


Solution

  • I faced the same issue and solved it by defining a Target (not Test Target) instead for Common.

    My Package.swift file:

    // ...
    .target(name: "Common", dependencies: ["App"], path: "Tests/Common"),
    .testTarget(name: "AppTests", dependencies: ["App", "Common"]),
    .testTarget(name: "IntegrationTests", dependencies: ["App", "Common"])
    // ...