douti0687 2017-07-05 18:37
浏览 6


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:


package main

import (

var a App 

func TestMain(m *testing.M) {
    a = App{}
    code := m.Run()

func TestRulesetGet(t *testing.T) {

    req, err := http.NewRequest("GET", "/1/sig/", nil)
    if err != nil {
    // 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 ",

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 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊