Beego 控制器 单元测试

1.在controllers文件目录中建立文件base_test.go,代码如下

package controllers

import (
    "fmt"
    "github.com/astaxie/beego"
    "github.com/astaxie/beego/context"
    "net/http"
    "net/url"
)

type testResponseWriter struct{}

func (f *testResponseWriter) Header() http.Header {
    return http.Header{}
}
func (f *testResponseWriter) Write(b []byte) (int, error) {
        //输出打印到终端
    fmt.Println(string(b))
    return 0, nil
}
func (f *testResponseWriter) WriteHeader(n int) {}

//构造控制器 BaseController是我项目的基础控制器,你可以换成你的,但必须继承自beego.Controller
func (c *BaseController) makeCtx() *BaseController {

    c.Ctx = context.NewContext()
    c.Ctx.Request = &http.Request{URL: &url.URL{Scheme: "http", Host: "localhost", Path: "/"}}
    c.Ctx.ResponseWriter = &context.Response{ResponseWriter: &testResponseWriter{}, Started: true}

    c.Ctx.Input.Context = c.Ctx
    c.Ctx.Input.RequestBody = []byte{}

    c.Ctx.Output.Context = c.Ctx

    c.Data = map[interface{}]interface{}{}

    return c
}

//阻止控制器中调用this.StopRun 而导致的panic
func recoverUserStop() {
    if err := recover(); err == beego.ErrAbort {
        return
    } else {
        panic(err)
    }
}


2.调用示例

func TestClientController_List(t *testing.T) {
    defer recoverUserStop()
    this := new(ClientController)

    this.makeCtx()

    this.List()
}

}

你可能感兴趣的:(Beego 控制器 单元测试)