---
title: "#133: Code Coverage in Xcode 🛠"
url: https://littlebitesofcocoa.com/133-code-coverage-in-xcode
author: Jake Marsh
date: 2015-11-25
published: 2015-11-25
topics: ["Tools","Testing"]
description: "Code Coverage arrived with Xcode 7. It can help us visualize which parts of our code are not being tested enough (or at all)."
---

# #133: Code Coverage in Xcode 🛠

By Jake Marsh, November 25, 2015. HTML: https://littlebitesofcocoa.com/133-code-coverage-in-xcode

_Code Coverage_ arrived with **Xcode 7**. It can help us visualize which parts of our code are not being tested enough (or at all). Let's dive in:

Before we can take advantage of _Code Coverage_, we'll need to enable it for our project. It's off by default.

We'll begin by editing our **scheme**, then selecting **Test** in the sidebar, then enabling the <i>Gather coverage data</i> **checkbox**.

<img src='https://media.littlebitesofcocoa.com/bite-assets/133-code-coverage-in-xcode-enable.png' style='max-width: 417px;' />

Now we'll run our tests by going to **Product** > **Test** in the menu (or pressing **U**). Then we can check out the test log where we'll find a new <i>“Coverage”</i> tab.

<img src='https://media.littlebitesofcocoa.com/bite-assets/133-code-coverage-in-xcode-coverage.png' style='max-width: 420px;' />

**Xcode** will display all the functions in our code with a bar graph indicating how well “covered” they are by our tests (We can mouse over to get an exact percentage). In our case, we are at 0%, since we don't have any tests. Yikes! Let's fix that by adding a simple test for a function on our `PersonViewModel`:

``` swift
func testFullName() {
  let person = Person(firstName: "Han", lastName: "Solo")
  let personVM = PersonViewModel(person: person)
  XCTAssertEqual(personVM.fullName, "Han Solo")
}
```

If we run our tests again, and check the <i>Coverage</i> tab, we can see we now have 50% test coverage for our tiny example project.

<img src='https://media.littlebitesofcocoa.com/bite-assets/133-code-coverage-in-xcode-final.png' style='max-width: 396px;' />

Last but not least, **Xcode** will also give us a heads up with a red shaded area in the right gutter on lines of code that aren't covered by our tests. Neat!
