Can we unit test specific target?

If we have a Swift package with multiple libraries and targets,
we can build specific target using command swift build --target TargetName.
Do we have any option to execute unit test cases of specific target using command like swift test --target TargetName?

1 Like

It’s not perfect but this technique works well for us:

Assuming you have two targets Foo and Bar with test targets FooUnitTests and BarUnitTests, then you can do

swift test --filter FooUnitTests
swift test --filter BarUnitTests
2 Likes

Even if I execute test with filter, it builds other targets as well.
One of the target contains UIKit related code, so the build gets failed.
Please find the reference repository containing swift package here
I tried the following command
swift test --filter FoundationExtensionTests

Have you tried --test-product?

  --test-product <test-product>
                          Test the specified product. 
1 Like

You should also try the --skip-build option of swift test.

1 Like

Have you tried --test-product ?

I tried swift test --test-product TargetName --skip-build, I got the following error,

error: no tests found; create a target in the 'Tests' directory

Then,

You should also try the --skip-build option of swift test .

I tried swift test --filter MyTarget --skip-build, I got the following error,

error: unableToLoadBundle("/Path/to/MyPackage/.build/x86_64-apple-macosx/debug/MyPackageTests.xctest")

Hi @jvigneshcs. If you need a code coverage report, you can just run tests for all targets but filter out the report itself.

Here is how you can show the report on a terminal:

llvm-cov report \
    .build/debug/YourProjectTests.xctest/Contents/MacOS/YourProjectTests \
    -instr-profile=.build/debug/codecov/default.profdata \
    -ignore-filename-regex=".build|Tests" \
    -use-color

But, if you want to export to a file and send it to some reporting tool like Codecov, you can do like this:

llvm-cov export -format="lcov" \
    .build/debug/YourProjectTests.xctest/Contents/MacOS/YourProjectPackageTests \
    -instr-profile=.build/debug/codecov/default.profdata \
    -ignore-filename-regex=".build|Tests" \
    > coverage.lcov

For a working solution using Github Actions, see Chaqmoq Workflow

1 Like