matlabmann 2018-06-26 11:12
浏览 44
已采纳

无法在Golang中测试模板

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

- This is my controller function that execute template. - In controller test func i have created a mock server that hits for a particular URL. -On running get test -v command i am getting this---- FAIL: TestGetItem (0.00s) panic: runtime error: invalid memory address or nil pointer dereference [recovered] panic: runtime error: invalid memory address or nil pointer dereference [signal SIGSEGV: segmentation violation code=0x1 addr=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条回答 默认 最新

  • dongtun1683 2018-06-27 09:55
    关注

    If you want to test a method that contains template which is executing inside that particular method then you have to provide the absolute path.

    Follow these steps:

    1. Set current working directory in your terminal:

      export varname="absolutepath"
      

      For example:

      export PATH="/go/src/github.com/project1"
      
    2. Use this command in your terminal:

      echo $varname
      

      For example:

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

      It will give you full path that you have set.

    3. In your program use this:

      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)
      
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000