2017-03-05 128 views
0

在大多數我見過的文檔中,大猩猩MUX建議像這樣使用...golang大猩猩/ MUX和測試,其中保存的路線

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

這是偉大的,但它給我留下有一個問題,因爲那時爲了測試,據我所看到的,我需要重新聲明MUX和路線,除非我宣佈MUX和這樣的功能的航線外...

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

,然後在我的測試是這樣做的...

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

它解決了這個問題,但它使包非常醜陋(與所有_ = m.HandleFunc's)有沒有更習慣的方式來做到這一點?

回答

2

您可以使用工廠功能爲您的應用程序創建新的http.Handler。這將允許您以編程方式定義處理程序並在測試中重新使用它們。

// 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!")) 
} 

此示例將在測試中利用像這樣:

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) 
    } 

}