Go
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions and Methods
-
Section 4: Concurrency
-
Section 5: Packages and Tooling
-
Section 6: More Standard Library
-
Section 7: Building Services
-
Section 8: Advanced Go
-
Section 9: Go in the Cloud-Native Ecosystem
-
Section 10: Data Structures and Algorithms in Go
-
Section 11: Testing and Deployment
-
Section 12: Practical Projects
-
Section 13: More Standard Library Practice
-
Section 14: More Practice Projects
-
Section 15: Design Patterns in Go
-
Section 16: Interview Practice
-
Section 17: Package fmt In Depth
-
Section 18: Package strings and strconv
-
Section 19: Package os and io
-
Section 20: Package time
-
Section 21: Package sort and container
-
Section 22: Package encoding
-
Section 23: Package net/http In Depth
-
Section 24: Package context
-
Section 25: Package regexp and bytes
-
Section 26: Package errors In Depth
-
Section 27: Package crypto and hash
-
Section 28: Package flag and log
-
Section 29: Package sync In Depth
-
Section 30: More Practice Exercises
-
Section 31: Go Modules and Workspaces In Depth
-
Section 32: Generics Deep Dive (Go 1.18+)
-
Section 33: Testing Package In Depth
-
Section 34: More Interview and Whiteboard Practice
-
Section 35: Package math and unicode
-
Section 36: Package path and filepath
-
Section 37: Package database/sql
-
Section 38: Package text/template and html/template
-
Section 39: Package archive and compress
-
Section 40: Lower-Level net Package
-
Section 41: Package runtime and reflect
-
Section 42: Package embed and io/fs
-
Section 43: Go Assembly and CGO Basics
-
Section 44: Building CLIs and TUIs
-
Section 45: Go Performance Tuning
-
Section 46: More Real-World Projects
-
Section 47: Go in Production
-
Section 48: Go Design Patterns
-
Section 49: Go Interfaces Deep Dive
-
Section 50: Final Practice and Review
75: Writing Tests with the testing Package
I see this all the time: developers coming from Java, Python, or JavaScript feel like Go's testing is "missing" something because there's no built-in expect() or assert.Equal(). They spend their first few days searching for the "official" assertion library because writing if got != want { t.Errorf(...) } feels repetitive, verbose, and—to some—primitive.
The "Too Verbose" Myth vs. Precise Failure Messages
The misconception is that a shorthand assertion like assert(got == want) is superior because it's shorter. But here is why that's wrong: assertions usually give you a generic "expected X, got Y" message. In a complex system, that's often useless. When a test fails in a CI pipeline at 3 AM, you don't want to know that a boolean was false; you want to know exactly which input caused the failure and why the state was invalid.
Let's look at a real example. Imagine we're writing a function to calculate a discount based on a user's membership level and the total purchase amount.
package discounts
func CalculateDiscount(level string, amount float64) float64 {
if level == "Gold" && amount > 100 {
return amount * 0.20
}
if level == "Silver" && amount > 100 {
return amount * 0.10
}
return 0
}
If we used a generic assertion library, a failure might look like: Expected 20.0, got 0.0. That's okay, but Go's explicit approach allows us to write a failure message that actually mentors the person fixing the bug.
func TestCalculateDiscount(t *testing.T) {
got := CalculateDiscount("Gold", 150.0)
want := 30.0
if got != want {
t.Errorf("CalculateDiscount(Gold, 150.0) = %.2f; want %.2f", got, want)
}
}
By writing the if block manually, I'm controlling the narrative. I'm telling the future maintainer exactly what the inputs were and what the outcome was. It's a bit more typing upfront, but it saves hours of debugging later. I've found that once you embrace this, you stop missing the "magic" of assertion libraries.
Scaling Logic with Table-Driven Tests
Now, you might be thinking, "Sure, one test is fine, but if I have ten edge cases, I'm going to have ten if blocks? That's insane." You're right. That's where Table-Driven Tests come in. This is the idiomatic way to write tests in Go. Instead of writing ten different functions, we define a slice of anonymous structs containing our inputs and expected outputs.
I use this pattern in almost every professional project I touch. It keeps the test logic separate from the test data.
func TestCalculateDiscountTable(t *testing.T) {
tests := []struct {
name string
level string
amount float64
expected float64
}{
{"Gold high spend", "Gold", 150.0, 30.0},
{"Gold low spend", "Gold", 50.0, 0.0},
{"Silver high spend", "Silver", 150.0, 15.0},
{"Bronze high spend", "Bronze", 150.0, 0.0},
{"Empty level", "", 150.0, 0.0},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got := CalculateDiscount(tc.level, tc.amount)
if got != tc.expected {
t.Errorf("%s: got %.2f, want %.2f", tc.name, got, tc.expected)
}
})
}
}
Notice the use of t.Run. This creates "subtests." If the "Silver high spend" case fails, Go will tell you exactly which subtest failed while continuing to run the others. This prevents one failure from masking other bugs in your logic. It turns your test file into a living specification of how your code is supposed to behave.
📋 Practical Task
Build a Table-Driven Test Suite for a Password Validator
You need to implement a password validation utility and ensure it is bulletproof using the techniques learned in this lesson.
The Requirements:
Write a function ValidatePassword(password string) bool that returns true only if:
- The password is at least 8 characters long.
- The password contains at least one digit.
Your Task:
- Implement the
ValidatePasswordfunction in a file namedauth.go. - Create a test file
auth_test.go. - Implement a Table-Driven Test that covers at least five scenarios:
- A valid password (should pass).
- A password that is too short (should fail).
- A password with no digits (should fail).
- An empty string (should fail).
- A password that is exactly 8 characters with a digit (should pass).
- Use
t.Runto name each test case clearly (e.g., "TooShort", "NoDigits"). - Ensure your
t.Errorfmessages explicitly state the input password that caused the failure.
There are no comments for now.