Eric Xu
Eric Xu

Reputation: 335

Unit testing Command Line Tool target in Xcode

I’ve been struggling for hours trying to find a way to unit test my code. There’s no way to select the main target (MazeGeneratorTests is there b/c I already created it).

Screenshot of test target creation dialog

Here’s what the Project Navigator looks like (don’t mind the random structure):

Project Navigator

After importing with @testable import MazeGenerator, calling anything from the module causes an Undefined symbols for architecture x86_64 error, e.g.:

func testPerformanceExample() throws {
    measure {
        let _ = generateNodes(rows: 20, cols: 20)
    }
}

Upvotes: 2

Views: 947

Answers (1)

Eric Xu
Eric Xu

Reputation: 335

Edit: I’ve realized that the better way to achieve this is by using a static library (see Library vs. Framework. Here’s an example repo showing how to achieve this: Imericxu/example-testable-swift-cli.

I figured it out. The “Command Line Tool” target is kind of finicky, so you need to separate all your logic into a new Framework target—this comes with a unit test target—and make everything you want to be visible public. Then build and import the framework into your main.swift file.

Upvotes: 4

Related Questions