I am new to Go and I am trying to write an unit test to check if the JSON data that I am retrieving from my API is being successfully marshalled into its respective objects.
I am using the go-resty API to make the request and the gock API to try to mock it.
Here is the function that I am trying to test:
func GetTasks() []Task {
resp, err := MakeRequest().
SetResult([]Task{}).
Get("http://my-api/task")
if err != nil {
log.Errorf("error when try to get tasks list %s", err)
return []Task{}
}
tasks := resp.Result()
t, ok := tasks.(*[]Task)
if ok != true {
log.Errorf("error when try convert tasks list response %s", ok)
return []Task{}
}
return *t
}
And here is the test code:
func Test_GetTasks(t *testing.T) {
testData, err := ioutil.ReadFile("../testdata/task-list.json")
if err != nil {
t.Error("Error retrieving json test data: %s", err)
t.Fail()
}
defer gock.Off()
gock.New("http://my-api").
Get("/task").
Reply(200).
JSON(testData)
var tasks []Task
tasks = GetTasks()
t.Logf("Tasks: %d", len(tasks))
if len(tasks) == 0 {
t.Error("No tasks were retrieved")
}
}
What I am doing wrong here?