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

时间:2017-07-05 18:37:46

标签: go

我有一个连接到数据库并检索记录的处理程序。我为此编写了一个测试用例,它就是这样的:

main_test.go

\d

我觉得这是一个非常基本的测试用例,我只是检查响应长度(这是因为我期望切片)。我不确定这是否是编写测试用例的正确方法。请指出一些循环漏洞,以便我可以为剩余的处理程序编写一个可靠的测试用例。而且,我没有使用实际的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()) } } Error方法来检查错误。

1 个答案:

答案 0 :(得分:0)

如果它有效,那么它没有错,但它没有多少验证,只是反应机构非空 - 甚至它没有成功。我不确定为什么会打印http.StatusOK,这是一个常数,并且不会告诉您响应中的状态代码是什么。

就个人而言,当我进行这个级别的测试时,我至少检查响应代码是否符合预期,响应正文解组正确(如果它是JSON或XML),响应数据基本上是正确的对于更复杂的有效负载,我可能会使用golden file测试。对于关键代码,我可能会使用fuzz (aka monte carlo) test。对于性能关键代码,我可能会添加基准测试和负载测试。几乎有无限的方法来测试代码。你必须弄清楚你的需求是什么以及如何满足它们。

相关问题