douti0687 2017-07-05 18:37
浏览 6
已采纳

在Go中测试连接到db的处理程序

I have a handler which connects to a db and retrieves the records. I wrote a test case for that and it goes this way:

main_test.go

package main

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

var a App 

func TestMain(m *testing.M) {
    a = App{}
    a.InitializeDB(fmt.Sprintf("postgres://****:****@localhost/db?sslmode=disable"))
    code := m.Run()
    os.Exit(code)
}


func TestRulesetGet(t *testing.T) {

    req, err := http.NewRequest("GET", "/1/sig/", nil)
    if err != nil {
        t.Fatal(err)
    }
    // We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response.
    rr := httptest.NewRecorder()
    handler := http.HandlerFunc(a.Get)
    handler.ServeHTTP(rr, req)

    // Check the response body is what we expect.

    if len(rr.Body.String()) != 0 {
      fmt.Println("Status OK : ", http.StatusOK)
        fmt.Println("handler returned body: got ",
            rr.Body.String())
    }
}

I feel like this is a very basic test case where I'm just checking the response length (This is because I expect a slice). I'm not really sure whether this is the right way to write a test case. Please point out some loop holes so that I could write a solid test cases for my remaining handlers. And also, I'm not using the actual Error, and Fatal methods for checking the errors.

  • 写回答

1条回答 默认 最新

  • dtt83024 2017-07-05 18:54
    关注

    If it works then it's not wrong, but it doesn't validate much, only that the response body is non-empty - not even that it's successful. I'm not sure why it prints out http.StatusOK, which is a constant, and doesn't tell you what the status code in the response was.

    Personally when I do this level of test I check, at the very least, that the response code is as expected, the response body unmarshals correctly (if it's JSON or XML), the response data is basically sane, etc. For more complex payloads I might use a golden file test. For critical code I might use a fuzz (aka monte carlo) test. For performance-critical code I'll likely add benchmarks and load tests. There are practically infinite ways to test code. You'll have to figure out what your needs are and how to meet them.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵