200 with user data → you change an auth middleware → test fails → you know before shipping.{ name: string } but the API now returns { fullName: string } → test fails → caught before the user sees a broken UI.assert the returned total is correct given these inputsassert that this specific internal function was called with these exact arguments10 BTC → balance is 10 BTC.t.Fatal when a failure makes all subsequent assertions meaningless (e.g. if parsing failed, don't keep asserting on the result).t.Errorf when you want to report a failure but still finish running the rest of the test.Go's built-in support for unit testing makes it easier to test as you go, check it out.
Test Driven Development (TDD) discipline: Write a failing test, make the compiler pass, run the test, write enough code to make the test pass, refactor.
In Go, test functions must start with Test followed by a capitalized name (like TestHello) and take a single parameter of type testing.T which provides methods for reporting test failures and logging.
go test, it compiles all .go files in the package (package main for example) and links them together into a single test binary. So if you have hello_test.go and hello.go part of the same package, they are linked and can access each other's functions.xxx_test.go, the test function must start with the word Test, and test function takes one argument only t *testing.T.Subtests allow you to group and run related test cases (using t.Run for example).
t.Run("saying hello to people", func(t *testing.T) {
got := Hello("Chris")
want := "Hello, Chris"
if got != want {
t.Errorf("got %q want %q", got, want)
}
})
t.Helper() marks a function as a test helper. When a test fails, the error message will point to the line in the test function rather than inside the helper function, making debugging easier.
Test Driven Development (TDD) loop:
It should not be a goal to have as many tests as possible, but rather to have as much confidence as possible in your code base. Having too many tests can add more overhead in maintenance. Every test has a cost.