DEV Community

Juma
Juma

Posted on

Testing Your API

A QA Mindset for Backend Developers

A developer and a tester walk up to the same door. The developer checks that the key opens it, nods, and walks through. The tester tries the key, then the wrong key, then no key, then the window, then asks what happens if two people come through at the same time, then wonders why the door has a gap underneath it big enough for a cat, and whether the cat has permission.

Both are doing valuable work. But the second mindset is the one that finds the bugs your users would otherwise find for you, at inconvenient hours. This article is about borrowing that mindset: how to test a whole API like a quality-minded engineer, using both Go's tooling and plain old curiosity.

The shift: from "does it work?" to "how could it break?"

When you write a feature, you naturally test the happy path. Of course you do. You built it to work that way. Your brain is wired to confirm.

Quality thinking flips the question. Instead of "does this work?", ask "under what conditions would this fail, and what would happen when it does?" You're not being pessimistic. You're being a friendly adversary, the sparring partner who throws the awkward punches in practice so the real fight is easy.

A few habits of that mindset:

  • Assume the input is wrong, strange, or hostile.
  • Assume the dependency will be slow, down, or confused.
  • Assume users will do things in the "wrong" order.
  • Ask "what did we forget to decide?" Missing requirements are bugs too, just earlier ones.

Where API tests fit: the testing pyramid

Picture a pyramid with three layers.

Bottom, wide: unit tests. Hundreds of fast checks on individual functions and services (the previous article). Cheap and precise.

Middle: integration and API tests. Dozens of tests that send real HTTP requests through your handlers, middleware, services, and a real database. They verify the pieces fit together.

Top, narrow: end-to-end tests. A few tests that drive the whole system like a user, perhaps through a browser. Valuable, but slow and brittle, so keep them few.

Most of your bug-hunting leverage for a backend lives in that middle layer. Unit tests prove the chef cooks correctly. API tests prove the waiter delivers the right dish to the right table, in the right language, and doesn't hand a stranger someone else's order.

Testing handlers in Go with httptest

Go ships with net/http/httptest, which lets you fire requests at your router without starting a real server or opening a port. Your Gin engine is just an http.Handler, so we can call it directly.

First, make your router constructable in a function (this is good design anyway):

func NewRouter(h *Handlers, tokens *auth.TokenService) *gin.Engine {
    r := gin.New()
    r.Use(gin.Recovery())

    api := r.Group("/api/v1")
    api.POST("/register", h.User.Register)
    api.POST("/login", h.User.Login)

    private := api.Group("")
    private.Use(RequireAuth(tokens))
    private.GET("/me", h.User.Me)
    return r
}
Enter fullscreen mode Exit fullscreen mode

Now a test:

func TestRegister_Endpoint(t *testing.T) {
    gin.SetMode(gin.TestMode)
    router := newTestRouter(t) // wires fakes or a test database

    body := `{"email":"amina@example.com","password":"correct-horse-9"}`
    req := httptest.NewRequest(http.MethodPost, "/api/v1/register",
        strings.NewReader(body))
    req.Header.Set("Content-Type", "application/json")

    rec := httptest.NewRecorder()
    router.ServeHTTP(rec, req)

    if rec.Code != http.StatusCreated {
        t.Fatalf("status = %d, want 201; body: %s", rec.Code, rec.Body.String())
    }

    var resp map[string]any
    if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
        t.Fatalf("response is not valid JSON: %v", err)
    }
    if _, leaked := resp["password_hash"]; leaked {
        t.Error("response must never include password_hash")
    }
}
Enter fullscreen mode Exit fullscreen mode

httptest.NewRequest builds a fake request. httptest.NewRecorder captures the response. ServeHTTP runs your whole stack: middleware, binding, handler, serialization. Notice the last assertion: it checks something users should never see. Negative assertions like this are pure tester thinking.

A little helper to cut the boilerplate

func doJSON(t *testing.T, r http.Handler, method, path, token, body string) *httptest.ResponseRecorder {
    t.Helper()
    req := httptest.NewRequest(method, path, strings.NewReader(body))
    req.Header.Set("Content-Type", "application/json")
    if token != "" {
        req.Header.Set("Authorization", "Bearer "+token)
    }
    rec := httptest.NewRecorder()
    r.ServeHTTP(rec, req)
    return rec
}
Enter fullscreen mode Exit fullscreen mode

Now each test is two or three readable lines. Good tests are cheap to write, and cheap tests get written.

A checklist for every endpoint

Here's where the QA mindset becomes practical. For each endpoint you build, walk through these questions. I keep a version of this list in my head, and it finds something nearly every time.

1. Happy path

Valid input returns the right status code, correct body, correct headers. Data actually persisted, if it should be.

2. Validation

  • Missing required fields
  • Empty strings and whitespace-only strings
  • Wrong types (a string where a number belongs)
  • Malformed JSON, or an empty body
  • Fields too long, too short
  • Unknown extra fields

3. Boundaries

This is the classic technique: test at the edges, because that's where off-by-one bugs live. If a password must be 8 to 72 characters, test 7, 8, 72, and 73. If limit is capped at 100, try 0, 1, 100, 101, and -1. Bugs love boundaries the way cats love sunbeams.

4. Authentication

  • No token
  • Malformed token (Bearer, then nothing)
  • Expired token
  • Token signed with the wrong key
  • A valid token for a deleted user

5. Authorization

Authentication asks who are you? Authorization asks are you allowed? Test it separately. Can user A read user B's order? Can a normal member hit an admin endpoint? This family of bugs, accessing things by changing an ID in the URL, is common and serious. A table test over "actor × resource × expected status" catches a lot.

6. Not found and conflict

Valid format but nonexistent ID returns 404. Duplicate creation returns 409. Does deleting something twice behave sensibly?

7. State and ordering

Cancel an order that's already shipped. Pay for an order twice. Update something after deleting it. Systems with states are full of illegal transitions, so enumerate them.

8. Idempotency and repetition

What if the client retries because the network hiccuped? If a POST creating an order is sent twice, do you get two orders? For payments and similar actions, that's a real-money question. Consider idempotency keys.

9. Concurrency

Two simultaneous requests to buy the last item in stock. Two users registering the same email at the same instant. The unique constraint from the PostgreSQL article is your safety net, but test that the net holds.

10. Data exposure

Does any response leak password hashes, internal IDs you meant to hide, other users' data, or stack traces? Read your responses with suspicious eyes.

11. Failure behavior

What happens when the database is down? When an external service times out? A well-behaved API returns a clean 5xx with no secrets, not a hung connection or a stack dump.

You won't test every item for every endpoint. But running through the list takes two minutes and surfaces the questions you hadn't asked.

Table-driven API tests

The table style from the last article is perfect here. One test, many scenarios:

func TestRegister_Validation(t *testing.T) {
    router := newTestRouter(t)

    tests := []struct {
        name   string
        body   string
        status int
    }{
        {"valid", `{"email":"a@b.com","password":"longenough1"}`, 201},
        {"missing email", `{"password":"longenough1"}`, 422},
        {"bad email", `{"email":"nope","password":"longenough1"}`, 422},
        {"password too short", `{"email":"a@b.com","password":"short"}`, 422},
        {"password at minimum", `{"email":"c@d.com","password":"12345678"}`, 201},
        {"empty body", ``, 400},
        {"malformed json", `{"email":`, 400},
        {"wrong type", `{"email":123,"password":"longenough1"}`, 400},
    }

    for _, tc := range tests {
        t.Run(tc.name, func(t *testing.T) {
            rec := doJSON(t, router, "POST", "/api/v1/register", "", tc.body)
            if rec.Code != tc.status {
                t.Errorf("status = %d, want %d; body: %s",
                    rec.Code, tc.status, rec.Body.String())
            }
        })
    }
}
Enter fullscreen mode Exit fullscreen mode

Eight scenarios, one function, readable like a specification. Notice the row labeled "password at minimum": that's boundary testing in action.

Testing authorization properly

Here's a pattern for the "can user A touch user B's stuff?" bug family:

func TestOrders_CannotReadOthersOrders(t *testing.T) {
    router, tokens := newTestRouterWithTokens(t)

    aliceToken := tokens.MustIssue(1, "member")
    bobToken := tokens.MustIssue(2, "member")

    // Alice creates an order
    rec := doJSON(t, router, "POST", "/api/v1/orders", aliceToken, orderJSON)
    id := extractID(t, rec)

    // Bob tries to read it
    rec = doJSON(t, router, "GET", "/api/v1/orders/"+id, bobToken, "")

    if rec.Code != http.StatusForbidden && rec.Code != http.StatusNotFound {
        t.Fatalf("Bob got status %d reading Alice's order; want 403 or 404", rec.Code)
    }
}
Enter fullscreen mode Exit fullscreen mode

Many teams prefer returning 404 over 403 here, so the API doesn't even confirm that Alice's order exists. Whichever you choose, decide deliberately, and pin it with a test.

Using a real database in API tests

Fakes are great for unit tests, but API tests earn their value by exercising the real stack, including your SQL, constraints, and migrations. A sturdy approach:

  1. Spin up a PostgreSQL instance for tests (Docker Compose, or testcontainers-go).
  2. Run your migrations against it.
  3. Wrap each test in a transaction that rolls back, or truncate tables between tests, so every test starts clean.
func resetDB(t *testing.T, db *gorm.DB) {
    t.Helper()
    db.Exec("TRUNCATE users, orders, order_items RESTART IDENTITY CASCADE")
}
Enter fullscreen mode Exit fullscreen mode

Isolation is the whole game. If test 7 depends on data left behind by test 3, you've built a haunted house.

Manual and exploratory testing: still worth doing

Automation checks what you thought of. Exploratory testing finds what you didn't. Spend ten unscripted minutes poking at a new endpoint with curl, Postman, or a similar client:

curl -i -X POST http://localhost:8080/api/v1/register \
  -H "Content-Type: application/json" \
  -d '{"email":"test@example.com","password":"password123"}'
Enter fullscreen mode Exit fullscreen mode

The -i flag shows headers, which often reveal surprises: a missing Content-Type, a weird cache header, a stack trace in a 500.

Try the rude things. Send 10,000 characters in a field. Send emoji. Send the same request ten times in a row. Send null for everything. Change a number to a negative. Delete the Authorization header halfway through a flow. When something strange happens, that's a bug worth understanding, and often one worth turning into an automated test so it stays fixed.

Writing a good bug report (for yourself and others)

When you find a defect, capture it so it can be fixed without a detective novel:

  • Title: specific. "POST /orders returns 500 when items array is empty," not "orders broken."
  • Steps to reproduce: exact request, headers, body.
  • Expected result: what should have happened.
  • Actual result: what did, including status code and body.
  • Environment: version, branch, database state.
  • Evidence: logs, response, timestamps.

Then write the failing test first, fix the code, and watch it go green. That sequence, red then green, gives you a fix you can prove and a regression guard for free.

Test data and environments

A few hygiene points that quietly decide whether a test suite is pleasant or miserable:

  • Make test data obviously fake and unique per test (random suffixes on emails) to avoid collisions.
  • Never run tests against production. Ever. Not "just read-only." A typo is all it takes.
  • Keep environments similar. If tests run on SQLite but production uses PostgreSQL, you're testing a different animal.
  • Run the suite in CI on every push, so "it passed on my machine" stops being a defense.

Common mistakes

Only testing the happy path. The success case is the one scenario already known to work.

Asserting only the status code. A 200 with the wrong body is still a bug. Check the payload, and check what's absent.

Skipping authorization tests. Broken access control sits near the top of security risk lists for good reason.

Tests coupled to each other. Shared leftover data creates order-dependent failures.

Brittle assertions. Comparing whole JSON strings character by character breaks when someone adds a harmless field. Assert on the parts that matter.

No concurrency thinking. Race conditions don't show up in single-request tests.

Treating testing as someone else's job. The person who writes the code knows its weak spots better than anyone. Test it like you're trying to win an argument against yourself.

Quick recap

  • Quality thinking asks "how could this break?" and not just "does it work?"
  • API tests sit in the middle of the pyramid, and httptest lets you run your whole router without a server.
  • Walk each endpoint through the checklist: validation, boundaries, auth, authorization, state, idempotency, concurrency, data exposure, and failure behavior.
  • Table-driven tests keep many scenarios readable, and boundary values catch off-by-one bugs.
  • Test authorization explicitly, especially "can user A touch user B's data?"
  • Use a real PostgreSQL for API tests, with clean isolation between them.
  • Mix automation with exploratory poking, and turn discoveries into regression tests.
  • Report bugs with exact steps, expected, and actual results.

Top comments (0)