'What do I wrong while coding GORM API Unit Test?

A few days ago, I started learning Golang, PostgreSQL, and Unit tests. I searched a lot of information about how to API unit test in GORM here and there. I just tried to follow up Golang documentation (https://go.dev/src/net/http/httptest/example_test.go) and one of the StackOverflow posts (https://codeburst.io/unit-testing-for-rest-apis-in-go-86c70dada52d)

I am not sure I got this error message "undefined: RegisterTodoListRoutes".

handler := http.HandlerFunc(RegisterTodoListRoutes) in this line 

My todolist-routes.go code is

package routes

import (
    "github.com/gorilla/mux"
    "github.com/jiwanjeon/go-todolist/pkg/controllers"
)

var RegisterTodoListRoutes = func (router *mux.Router){
    router.HandleFunc("/todo/", controllers.CreateTodo).Methods("POST")
    router.HandleFunc("/todo/", controllers.GetTodo).Methods("GET")
    router.HandleFunc("/todo/{todoId}", controllers.GetTodoById).Methods("GET")
    router.HandleFunc("/todo/{todoId}", controllers.UpdateTodo).Methods("PUT")
    router.HandleFunc("/todo/{todoId}", controllers.DeleteTodo).Methods("DELETE")
    router.HandleFunc("/complete/{todoId}", controllers.CompleteTodo).Methods("PUT")
    router.HandleFunc("/incomplete/{todoId}", controllers.InCompleteTodo).Methods("PUT")
} 

and my todolist-routes_test.go test code is

package routes_test

import (
    "net/http/httptest"
    "testing"
    "net/http"
    
)

func TestRegisterTodoListRoutes(t *testing.T) {
    req, err := http.NewRequest("GET", "/todo/", nil)
    if err != nil {
        t.Fatal(err)
    }
    rr := httptest.NewRecorder()
    handler := http.HandlerFunc(RegisterTodoListRoutes)

        handler.ServeHTTP(rr, req)

  // Check the status code is what we expect.
  if status := rr.Code; status != http.StatusOK {
      t.Errorf("handler returned wrong status code: got %v want %v",
          status, http.StatusOK)
    }
    
    expected := `[{"ID":46,"title":"test-title-console-check","last_name":"test-description-console-check", "conditions": true]`
    if rr.Body.String() != expected {
        t.Errorf("handler returned unexpected body: got %v want %v",
            rr.Body.String(), expected)
    }
}

Here is a link for todolist_routes.go : https://go.dev/play/p/XoVMbK7PnLu this is for test code : https://go.dev/play/p/NddwrU5m6ss

I really appreciate your help!!

Edit 1] I found the reason why I got this error. When I remove _test above at package and run it. I got this error "cannot convert Routes (type func(*mux.Router)) to type http.HandlerFunc"



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source