douji9518 2017-09-14 05:48
浏览 68
已采纳

测试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!

  • 写回答

1条回答 默认 最新

  • dongliu4320 2017-09-14 09:20
    关注

    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)
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?