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.

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

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?