beego与gin的覆盖率测试
beego的测试
改进的内容:
func prepareController(c *beego.Controller) {
c.Ctx = &context.Context{
Request: &http.Request{URL: &url.URL{Scheme: "http", Host: "localhost",Path:"/mypath"}},
//ResponseWriter: &fakeResponseWriter1{},
ResponseWriter: &context.Response{ResponseWriter:&fakeResponseWriter1{}},
}
c.Ctx.Output = &context.BeegoOutput{Context: c.Ctx}
//c.Ctx.Input = &context.BeegoInput{Request: c.Ctx.Request}
c.Ctx.Input = &context.BeegoInput{Context: c.Ctx}
//globalSessions, _ := session.NewManager("memory", `{"cookieName":"gosessionid","gclifetime":10}`)
globalSessions, _ := session.NewManager("memory", &session.ManagerConfig{CookieName:"gosessionid",Gclifetime:10})
c.Ctx.Request.Header = http.Header{}
c.Ctx.Request.AddCookie(&http.Cookie{Name: "gosessionid", Value: "test"})
c.CruSession = globalSessions.SessionRegenerateID(c.Ctx.ResponseWriter, c.Ctx.Request)
c.Data = map[interface{}]interface{}{}
}
type fakeResponseWriter1 struct{}
func (f *fakeResponseWriter1) Header() http.Header {
return http.Header{}
}
func (f *fakeResponseWriter1) Write(b []byte) (int, error) {
return 0, nil
}
func (f *fakeResponseWriter1) WriteHeader(n int) {}
func TestHttpRequestNormalRequestHttpGET(t *testing.T) {
content:=`{
"aaa": "aaa",
"bbb": "bbb",
"ccc": {
"ddd": "ddd",
"eee": "eee"
},
"fff": "fff"
}`
c := &controllers.MyController{}
prepareController1(&(c.Controller))
// 需要携带的body信息
c.Ctx.Input.RequestBody=[]byte(content)
// 需要携带的header
c.Ctx.Request.Header["myheader"] = []string{"myRequestHeader"}
c.SetSession("login", "123")
c.Prepare()
// 对应的控制器函数
c.MyApi()
j:=c.Data["json"]
mapV:=reflect.ValueOf(j)
errV:=mapV.MapIndex(reflect.ValueOf("Error"))
if errV.IsValid() && errV.String() != "" {
t.Fatal("has error:", errV)
}
descriptionV:=mapV.MapIndex(reflect.ValueOf("description"))
if !descriptionV.IsValid() {
t.Fatal("no output data!")
} else {
fmt.Println(descriptionV.Interface().(string))
}
}
gin的测试
func TestMyApi(t *testing.T) {
//获得路由
router := routers.InitRouter()
m := make(map[string]interface{})
m["aaa"] = "aaa"
m["bbb"] = "bbb"
m["ccc"] = "ccc"
js,_:=json.Marshal(m)
b := bytes.NewBuffer(js)
w := httptest.NewRecorder()
req, _ := http.NewRequest("POST", "/path1/path2", b)
req.Header.Set("myheader1", "111")
req.Header.Set("myheader2", "222")
router.ServeHTTP(w, req)
resp := w.Result()
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(resp.StatusCode)
//获得结果,并检查
if len(body) == 0 {
fmt.Println("len body is 0")
}
}
go test -v -coverpkg ./... -coverprofile=c.out && go tool cover -html=c.out -o test.html
-coverpkg 后面是要统计覆盖率的文件源码目录
-coverprofile 覆盖率 profile 文件输出地址