测试golang的Web应用程序查询参数的最佳做法

In a simple case of two required parameters, there are four possible test cases IIUC:

  1. both empty
  2. first set but not second
  3. second set but not first
  4. both set

What is best practice, test all four cases?

Because even testing the first and last cases is quite verbose in Golang:

func TestGoodParameter(t *testing.T) {

        req, _ := http.NewRequest("GET", "/", nil)

        q := req.URL.Query()
        q.Add("first", "foo")
        q.Add("second", "bar")
        req.URL.RawQuery = q.Encode()

        rec := httptest.NewRecorder()
        root(rec, req)
        res := rec.Result()

        if res.StatusCode != http.StatusOK {
                t.Errorf("got %v, expected %v", res.StatusCode, http.StatusOK)
        }

}

func TestBadParameter(t *testing.T) {

        req, _ := http.NewRequest("GET", "/", nil)

        rec := httptest.NewRecorder()
        root(rec, req)
        res := rec.Result()

        if res.StatusCode != http.StatusBadRequest {
                t.Errorf("got %v, expected %v", res.StatusCode, http.StatusBadRequest)
        }

}

Or are there some tricks I am missing here? It obviously gets even more complicated when say there are five parameters where two of them are optional!

Define your test cases table driven way and write a single implementation for it. You can simplify definition by omitting the name of test cases.

package main

import (
    "net/http"
    "net/http/httptest"
    "testing"
)

func TestParameters(t *testing.T) {
    testCases := map[string]struct {
        params map[string]string
        statusCode int
    }{
        "good params": {
            map[string]string{
                "first": "foo", "second": "bar",
            },
            http.StatusOK,
        },
        "without params": {
            map[string]string{},
            http.StatusBadRequest,
        },
    }

    for tc, tp := range testCases {
        req, _ := http.NewRequest("GET", "/", nil)
        q := req.URL.Query()
        for k, v := range tp.params {
            q.Add(k, v)
        }
        req.URL.RawQuery = q.Encode()
        rec := httptest.NewRecorder()
        root(rec, req)
        res := rec.Result()
        if res.StatusCode != tp.statusCode {
            t.Errorf("`%v` failed, got %v, expected %v", tc, res.StatusCode, tp.statusCode)
        }
    }
}