Skip to Content
Course content

75: Writing Tests with the testing Package

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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:

  1. Implement the ValidatePassword function in a file named auth.go.
  2. Create a test file auth_test.go.
  3. 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).
  4. Use t.Run to name each test case clearly (e.g., "TooShort", "NoDigits").
  5. Ensure your t.Errorf messages explicitly state the input password that caused the failure.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.