download20151010 2017-03-05 07:21
浏览 48
已采纳

golang大猩猩/ mux和测试,在哪里存储路由

In most of the docs I have seen, gorilla mux is suggested to be used like so...

func main() {
    m := mux.Router()
    m.HandleFunc("/", FuncNameOrDef)
    http.ListenAndServe(":8080", m)
}

which is great, but it leaves me with a problem, because then in order to test, as far as I can see, I need to redeclare mux and routes unless I declare mux and routes outside of a function like this...

var (
    m = mux.Router()
    _ = m.HandleFunc("/", FuncNameOrDef)
)

and then in my tests do this...

func TestSomeView(t *testing.T) {
    ts := httptest.NewServer(m)
    ....testing blah
}

which solves the problem, but then it makes the package pretty ugly (with all the _ = m.HandleFunc's) Is there a more idiomatic way to do this?

  • 写回答

1条回答 默认 最新

  • dtmjl4427 2017-03-05 18:44
    关注

    You could use a factory function to create a new http.Handler for you application. This would allow you to programmatically define the handlers and reuse them in the tests.

    // NewApplicationHandler provides a configured handler for the
    // application.
    func NewApplicationHandler() http.Handler {
        mux := mux.NewRouter()
        mux.HandleFunc("/", handler)
    
        return mux
    }
    
    func handler(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Hello World!"))
    }
    

    This example would be utilized in a test like so:

    func TestApplicationServeMux(t *testing.T) {
        // The handlers are being obtained via a call to the factory function.
        applicationHandler := NewApplicationHandler()
    
        ts := httptest.NewServer(applicationHandler)
        defer ts.Close()
    
        res, err := http.Get(ts.URL)
    
        if err != nil {
            t.Fatalf("%s", err)
        }
    
        defer res.Body.Close()
        greeting, err := ioutil.ReadAll(res.Body)
    
        if err != nil {
            log.Fatalf("%s", err)
        }
    
        want := []byte("Hello World!")
    
        if !bytes.Equal(want, greeting) {
            t.Errorf("Expected greeting %s; got %s", want, greeting)
        }
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常
  • ¥15 关于风控系统,如何去选择