Unit Testing

https://blog.jetbrains.com/go/2022/11/22/comprehensive-guide-to-testing-in-go

How to do unit testing

  • Create file project_test.go

  • The test function signature is TestXXX(t *testing.T)

Those two steps are the only mandatory step to create unit testing. But we can follow some best practices to structure our tests and test cases:

  • Structure our test as test tables with many test cases

  • Properly assert the function behavior

  • Name test cases as descriptive as possible

Useful Commands

  • Use go test -race ./... to run the unit test with a check for a race condition

  • Use go tool cover -func=coverage.out to display coverage information on the terminal console

  • Use go tool cover -html=coverage.out to display the coverage information on HTML format in browser.

Examples

package main

import "strconv"

// If the number is divisible by 3, write "Foo" otherwise, the number
func Fooer(input int) string {

    isfoo := (input % 3) == 0

    if isfoo {
        return "Foo"
    }

    return strconv.Itoa(input)
}

project_test.go

Table Driven testing

Errors and Logs

Running Parallel Tests

The following code will test Fooer(3) and Fooer(7) at the same time

Skipping Tests

Last updated

Was this helpful?