10

On my M1 mac, using Xcode 13.3, I created a package and displayed the code coverage bar (Editor menu –> Code Coverage).

After running tests, there is no indication of code coverage at all in the source code.

How do I get code coverage when testing a package?

Aaron Bratcher
  • 6,051
  • 2
  • 39
  • 70

2 Answers2

8

The problem is that you didn't turn on Code Coverage for the library's scheme. Turn it on:

enter image description here

See the checkbox at the bottom: Code Coverage? Check that checkbox.

Now run the package test and coverage will be gathered. The best way to see it, in my experience, is actually in the report navigator:

enter image description here

Edit: In more modern Xcode (14.3 and later) it's simpler. Tests default to using test plans, so just turn on code coverage in the test plan:

enter image description here

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • 2
    This is no longer a valid answer. – WikipediaBrown Jun 10 '23 at 18:52
  • any update on this? – mikro098 Jun 12 '23 at 11:17
  • @mikro098 It's simpler now. Tests have test plans. Just turn on code coverage in the test plan and away you go. Packages are covered automatically. – matt Jun 12 '23 at 16:19
  • This is still a valid answer, there is just another way of accomplishing the same thing through the test plans. Checking the box in the test scheme inside Xcode still works just fine, I did it just now. – Brianna Doubt Jun 13 '23 at 14:10
  • 2
    @BriannaDoubt I think the objection was that the "Gather coverage" checkbox is no longer present in the scheme editor for new project. And that's true; test plans are the only alternative today. I encouraged WikipediaBrown to add the newer approach as an answer, but there was no response, so I appended it myself. – matt Jun 13 '23 at 14:12
  • Ah, my bad, didn't realize I wasn't on 14.3 :) Thanks Matt! – Brianna Doubt Jun 14 '23 at 13:35
4

As of (at least) Xcode 14, the former answer is no longer correct. For a Swift Package you need to enable this on the test plan.

Steps:

  1. Show Test Navigator (CMD + 6)
  2. Select the title, in the example: TestPlanExample and select "Edit Test Plan"

Select Edit Test Plan

  1. Select the tab "Configuration" and scroll down to "Code Coverage"
  2. Enable Code Coverage and either select "All targets" or select which targets you wish you generate code coverage for. Enable Code Coverage
  3. Save the testplan
Paul Peelen
  • 10,073
  • 15
  • 85
  • 168