DEV Community

Ankit malik
Ankit malik

Posted on • Edited on

How to Write Unit Test Cases for Golang

What is Unit Test?
Unit test is a way to test a unit. A unit can be a function or multiple function.

Why Test cases are important?
Test Cases are important because they give us and operation team confidence that our code will perform the way we want it to be performed. It is also good way to test our code with given input and expected output.

Test Cases in Golang
Golang has in-built testing library for the unit testing.
We can run the command go test. We can also this command go test ./... to run test cases for the whole project.

Find below example for writing the unit test case:

file: sum.go

package main

func Sum(a, b int) int {
    return a + b
}
Enter fullscreen mode Exit fullscreen mode

file: sum_test.go
We need to create test file with given format {{filename}}_test.go

package main

import (
    "testing"
)

func TestSum(t *testing.T) {
    result := Sum(10, 12)
    if result != 22 {
        t.Error("result is not equal")
    }
}

Enter fullscreen mode Exit fullscreen mode

Tabular Test Case

The better approach is to use tabular test cases because this is more elegant way to write the test cases.

package main

import (
    "testing"
)

func TestSum(t *testing.T) {
    tests := []struct {
        a      int
        b      int
        result int
    }{
        {
            a:      5,
            b:      6,
            result: 11,
        },
        {
            a:      3,
            b:      4,
            result: 7,
        },
        {
            a:      2,
            b:      8,
            result: 10,
        },
        {
            a:      9,
            b:      6,
            result: 15,
        },
        {
            a:      15,
            b:      666,
            result: 681,
        },
    }

    for _, testCase := range tests {
        result := Sum(testCase.a, testCase.b)
        if testCase.result != result {
            t.Errorf("Test case failed for given input a:%d & b:%d", testCase.a, testCase.b)
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Commands to Run the Test cases

  1. go test - to run the test cases for current package
  2. go test ./... - to run the test cases for whole project
  3. go test -v - to run the cases in verbose/detailed mode
  4. go test -cover - to show the test coverage
  5. go tool cover -html=c.out -o coverage.html - to generate the coverage in html file

Top comments (0)