Checking Test Coverage

Let's continue our journey into standard Golang testing and look into test coverage.

We'll cover the following

Checking the test coverage is super important because if your test coverage is incomplete, it is safe to assume that the uncovered parts are broken. You wouldn’t want to deploy broken code, so you better be aware of the test coverage and strive to 100%.

Checking test coverage

When writing tests for non-trivial code it’s important to make sure your tests actually cover the code. This is where code coverage comes in. Go supports code coverage by passing the -cover flag to the go test command.

To see it in action, let’s add some code to the CalcArea() function to check the width and the height individually and return more informative error messages:

func CalcArea(w, h int) (int, error) {
    if w == 0 {
      return 0, errors.New("the width can't be zero")  
    }    
    if h == 0 {
      return 0, errors.New("the height can't be zero")  
    }
    if w < 0 {
      return 0, errors.New("the width can't be negative")  
    }
    
    if h < 0 {
      return 0, errors.New("the height can't be negative")  
    }

    return w * h, nil
}

Then, running go test -v -cover shows the percentage of the code that the tests cover, which is 55.6%.

=== RUN   TestCalcAreaSuccess
--- PASS: TestCalcAreaSuccess (0.00s)
PASS
coverage: 55.6% of statements
ok  	_/usercode	0.003s

You can add more test cases or functions to try to get to 100% coverage.

Get hands-on with 1400+ tech skills courses.