Search code examples
swiftxcodeunit-testingpackageswift-package-manager

Is there a way to have unit test file at the same path of tested file in a Swift Package?


I want to have my unit test file at the same path of the tested file.

Using SPM I couldn't make it work. To make it clearer I want something like this:

Sources
 -- MyPackage
 ----- MyCode.swift
 ----- MyCodeTests.swift

Solution

  • Swift Package Manager is not designed for this kind of directory structure. Your tests and sources are in different targets, which are most easily declared by specifying a directory containing all the sources for that target.

    While it is technically possible to do this, it is not practical. You would need to list all the source files for your package, and the unit tests, separately, as the files for different targets cannot overlap.

    This means that you would need to edit Package.swift every time you add/remove/rename a file.

    Here is an example:

    let package = Package(
        name: "MyPackage",
        targets: [
            .executableTarget(
                name: "MyPackage",
                sources: ["MyCode.swift", /* every other source file */]
            ),
            .testTarget(
                name: "MyPackageTests",
                dependencies: ["MyPackage"],
                path: "Sources/MyPackage",
                sources: ["MyCodeTests.swift", /* every other test file */]
            )
        ]
    )