Golang Testing

  • Create your package (ex converters.go) and add logic to the package

  • Create test file for your package. Name of the file should have the package name and ‘_test’ appended to it. (ex converters_test.go)

  • Test functions must start with ‘Test’ followed by the name of the test and should accept *testing.T parameter

  package converters

  import "testing"


  func TestBroken( t *testing.T) {
    if true != false {
      t.Error("expected", true, "got", false)
    }

    if 1+1 != 4 {
      t.Fatal("Can't proceed", 1+1, 4)
    }
  }

t.Fatal is an Error and fail

  • Running tests

    • all in folder: go test -v . or go test -v ./foldername/
    • go test -v -run Error .
    • -run regexp: run only those tests and examples matching the regular expression
    • -v : verbose
  • Testing HTTP

    • HTTP provides its own test objects. Randomizes the server port
    • package net/http/httptest
  • Factories and Helpers

  • Testing Concurrent Code

    • Testing coordination
    • Race conditions
    • Waiting for code to finish

https://blog.codeship.com/creating-fakes-in-go-with-channels/

Tips 1. Test from the outside 1. Test from the inside if you have to 1. Isolate with fakes and interfaces (good design anyways = win) 1. Tests are code too: use good programming patterns and refactor 1. Provide test helpers publicly