Running Go Tests

In this lesson, you will learn how to run tests using go test.

Running tests with go test

Now that we have some tests, let’s run them.

Running functional tests

Running Go tests is very easy. Just type go test. If you want a little more verbose output that lists the tests being run, type go test -v. If you run the test below, you’ll see this output:

=== RUN   TestCalcAreaSuccess
--- PASS: TestCalcAreaSuccess (0.00s)
=== RUN   TestCalcAreaFail
--- PASS: TestCalcAreaFail (0.00s)
=== RUN   TestCalcAreaViaTable
--- PASS: TestCalcAreaViaTable (0.00s)
PASS
ok  	_/usercode	0.003s
package main

import (
    "testing"
)

func TestCalcAreaSuccess(t *testing.T) {
    result, err := CalcArea(3, 5)
    if err != nil {
      t.Error("CalcArea(3, 5) returned an error")
    } else if result != 15 {
      t.Errorf("CalcArea(3, 5) returned %d. Expected 15", result)
    }
}

func TestCalcAreaFail(t *testing.T) {
    _, err := CalcArea(-3, 6)
    if err == nil {
      t.Error("Expected CalcArea(-3, 6) to return an error")
    }
        
    if err.Error() != errorMessage {
      t.Error("Expected error to be: " + errorMessage)      
    } 
}

func TestCalcAreaViaTable(t *testing.T) {
  var tests = []struct {
      width    int
      height   int
      expected   int
  }{
    {1, 1, 1},
    {5, 6, 30},
    {1, 99, 99},
    {7, 6, 42},
  }

  for _, test := range tests {
    w := test.width
    h := test.height
    r, err := CalcArea(w, h)
    if err != nil {
      t.Errorf("CalcArea(%d, %d) returned an error", w, h)
    } else if r != test.expected {
      t.Errorf("CalcArea(%d, %d) returned %d. Expected %d", 
                w, h, r, test.expected)
    }
  }  
}
Running go tests (verbose)

Let’s see what happens when tests fail… I’ve added two test ...