go - 无法在golang中测试模板

标签 go

//This is my controller test function that test for GET Item request  
    func TestGetItem(t *testing.T) {
        s := GetDockerItemControllerImpl{
            GetDockerService: GetItemReqSuccessImplTest{},
        }

        for _, test := range testCaseGetItemFullSuccess {
            router := mux.NewRouter()
            router.HandleFunc("/docker/config/{id}", s.GetDockerConfig())//this will run controller function GetDockerConfig()

            ts := httptest.NewServer(router)
            defer ts.Close()

            req, err := http.NewRequest(test.Method, test.URL, nil)

            if err != nil {
                t.Fatal(err)
            }
            rr := httptest.NewRecorder()
            router.ServeHTTP(rr, req)

            if status := rr.Code; status != test.expectStatus {
                t.Errorf("handler returned wrong status code: got %v want %v",
                    status, test.expectStatus)
            }

        }
    }

    //Controller function
        func (s *GetDockerItemControllerImpl) GetDockerConfig() http.HandlerFunc {
            return func(w http.ResponseWriter, req *http.Request) {
            var rootobject models.Root
            vars := mux.Vars(req)

            if bson.IsObjectIdHex(vars["id"]) {
            rootobject.ID = bson.ObjectIdHex(vars["id"])

            marshalData, unmarshalErr := json.Marshal(rootobject)
                if unmarshalErr != nil {
                http.Error(w, "Unprocessable Entity error", http.StatusUnprocessableEntity)
                return
                }

                rootobject, err := s.GetDockerService.GetItem(marshalData)
                if err != nil {
                http.Error(w, "Bad Request", http.StatusBadRequest)
                return
                }

                t, err := template.ParseFiles("./views/dockerconfigDetails.gtpl")
                if err != nil {
                http.Error(w, "Internal Server Error", http.StatusInternalServerError)
                return
                }

                t.ExecuteTemplate(w, "dockerconfigDetails.gtpl", rootobject)
                if err != nil {
                http.Error(w, "Record not found of this ID:"+vars["id"], http.StatusNotFound)
                return
                }
                } else {
                http.Error(w, "Invalid Id bad request", http.StatusBadRequest)
                }
            }}

- 这是我执行模板的 Controller 函数。 - 在 Controller 测试功能中,我创建了一个模拟服务器,它可以访问特定的 URL。 - 在运行 get test -v 命令时我得到这个----失败:TestGetItem(0.00s) panic :运行时错误:无效内存地址或 nil 指针取消引用 [已恢复] panic :运行时错误:无效的内存地址或零指针取消引用 [信号 SIGSEGV:分段违规代码=0x1 地址=0x20 pc=0x5927a0]

goroutine 9 [running]:
testing.tRunner.func1(0xc4201263c0)
        /home/webonise/niketa/go/src/testing/testing.go:711 +0x2d2
panic(0x7cc060, 0xa5bcc0)
        /home/webonise/niketa/go/src/runtime/panic.go:491 +0x283
html/template.(*Template).lookupAndEscapeTemplate(0x0, 0x845b99, 0x18, 0x0, 0x0, 0x0)
        /home/webonise/niketa/go/src/html/template/template.go:144 +0x50
html/template.(*Template).ExecuteTemplate(0x0, 0x7f9afab510e8, 0xc420060b80, 0x845b99, 0x18, 0x808400, 0xc42011c880, 0x0, 0x0)
        /home/webonise/niketa/go/src/html/template/template.go:133 +0x43
github.com/gror/controllers.(*GetDockerItemControllerImpl).GetDockerConfig.func1(0xa2f540, 0xc420060b80, 0xc42012a500)
        /home/webonise/go/src/github.com/gror/controllers/controller.go:149 +0x3ce
net/http.HandlerFunc.ServeHTTP(0xc4200472a0, 0xa2f540, 0xc420060b80, 0xc42012a500)
        /home/webonise/niketa/go/src/net/http/server.go:1918 +0x44
github.com/gorilla/mux.(*Router).ServeHTTP(0xc420128a80, 0xa2f540, 0xc420060b80, 0xc42012a500)
        /home/webonise/go/src/github.com/gorilla/mux/mux.go:162 +0xed
github.com/gror/controllers.TestGetItem(0xc4201263c0)
        /home/webonise/go/src/github.com/gror/controllers/controller_test.go:364 +0x500
testing.tRunner(0xc4201263c0, 0x8575a8)
        /home/webonise/niketa/go/src/testing/testing.go:746 +0xd0
created by testing.(*T).Run
        /home/webonise/niketa/go/src/testing/testing.go:789 +0x2de
exit status 2
FAIL    github.com/gror/controllers     0.007s

最佳答案

如果你想测试一个包含在特定方法中执行的模板的方法,那么你必须提供绝对路径。

请按照以下步骤操作:

  1. 在终端中设置当前工作目录:

    export varname="absolutepath"
    

    例如:

    export PATH="/go/src/github.com/project1"
    
  2. 在您的终端中使用此命令:

    echo $varname
    

    例如:

    echo $PATH
    /go/src/github.com/project1
    

    它将为您提供您设置的完整路径。

  3. 在你的程序中使用这个:

    path := os.Getenv("PATH")
    t, err := template.ParseFiles(Path + "views/dockerconfig.gtpl")
    if err != nil {
        fmt.Println(errors.New("unable to execute the template"))
    }
    t.Execute(w, nil)
    

关于go - 无法在golang中测试模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51041516/

相关文章:

Golang 百万分之一的概率

go - 未搜索 Html 模板文件

go - 如何使用 gorm 的反射类型来泛化 api 函数

go - 像谷歌地球一样重新着色图标

http - ResponseWriter.Write 返回的 int 是什么意思?

string - 如何在 GO 中操作字符串来反转它们?

oauth - 带有市场的 Admin-sdk 不起作用

go - 与 reflect.TypeOf 一起使用的空结构

json - 实现实体组件系统的最佳方式是什么

docker - Kubernetes:端口转发后,我可以通过 "localhost"访问服务,但不能通过 "hostname"访问服务