Skip to content

Instantly share code, notes, and snippets.

@anitsh
Created March 26, 2020 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anitsh/9cdba583ab37d1d041728b00b30ee7c3 to your computer and use it in GitHub Desktop.
Save anitsh/9cdba583ab37d1d041728b00b30ee7c3 to your computer and use it in GitHub Desktop.
Unit Test In Go

Unit Test In Go

Read Before: Understaing Unit Test In short, unit tests are codes focusing on a small part of the software system.

After understanding why developers needs to write unit tests, let's Go.

Go Official The official package of Go is here

// example_test.go File name must endup with `_test`

import "testing" // This is the package to import

func TestMyLogic(t *testing.T) { // Function name should start with word `Test` followed by a capital letter `My`
   // <setup code>
    t.Run("TestCase=A", func(t *testing.T) { ... }) // Subtest to test many usecases of the function. 
    ...
    t.Run("TestCase=X", func(t *testing.T) { ... })  
   // <tear-down code>
}

Commands to run the tests go test -run '' # Run all tests. go test -run MyLogic # Run top-level tests matching "Foo", such as "TestFooBar". go test -run Mylogic/TestCase=A # For top-level tests matching "Foo", run subtests matching "A=". go test -run /TestCase=A # For all top-level tests, run subtests matching "A=1".

Frameworks

There are a lot of few frameworks built in Go to help developers become productive. I will list them here and write examples in separate files.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment