วันอังคารที่ 23 กุมภาพันธ์ พ.ศ. 2559

[go lang] Unit test with gorilla/mux

นั่งงมทำ unit test บน go กับ lib gorilla/mux มาครึ่งวัน เพราะเวลายิง test แล้ว มันไม่สามารถดึงตัวแปรได้

โดยปรกติเวลาเราสร้าง router บน gorilla/mux เราจะสร้าง


rtr.HandleFunc("/v1/exp/{UUID}", GetProductExp).Methods("GET")
เวลาดึงค่าก็ใช้
params := mux.Vars(r)
fmt.Println(params["UUID"]

แต่เวลาเราทำ unit test มันจะทำให้ function handle ของเราดึง var ออกมาไม่ได้เพราะถ้าเขียน unit test ปรกติจะเขียนประมาณ

func TestGetProductExp(t *testing.T) {
        fmt.Println("Testing GetProductExp")
        request, _ := http.NewRequest("GET", "/v1/exp/21a56778-6aad-4d90-aa16-6b5748a9f717", nil)
        response := httptest.NewRecorder()
        GetProductExp(response, request)
        fmt.Println(response.Body)
}

แต่เมื่อสั่ง go test ไปแล้วผลปรากฏว่า funcHandle ที่เขียนไว้ดึงค่าไม่ได้ทั้งๆที่ลอง run program ดูจริงๆแล้วลองยิง req ดูจริงๆแล้วมันก็อ่านค่าตัวแปรได้
ตอนหาข้อมูลมีคนเจอปัญหาเหมือนผมด้วย http://mrgossett.com/post/mux-vars-problem/
นั่งหาอ่านอยู่เกือบครึ่งวันกว่าจะได้คำตอบว่า lib gorilla/mux มันแปลงค่าตัวแปรให้มาอยู่ในรูป map[string]string ทำให้เวลายิงผ่าน test มันแปลงข้อมูลผิด ถ้าจะทำ unit test กับ gorilla/mux ให้เขียน test ประมาณนี้

func TestGetProductExp(t *testing.T) {
        fmt.Println("Testing GetProductExp")
        request, _ := http.NewRequest("GET", "/v1/exp/21a56778-6aad-4d90-aa16-6b5748a9f717", nil)
        response := httptest.NewRecorder()
        m := mux.NewRouter()
        m.HandleFunc("/v1/exp/{UUID}", GetProductExp)
        m.ServeHTTP(response, request)
        fmt.Println(response.Body)
}

ไม่มีความคิดเห็น:

แสดงความคิดเห็น