request, err := http.NewRequest("GET", path, nil)
response := httptest.NewRecorder()
r.ServeHTTP(response, request)
var raw map[string]map[string]string
_ = json.Unmarshal(response.Body.Bytes(), &raw)
details := raw["response"]
I have a TestFunction in which I am using this code. It is code to test the REST API for a GET request.
In my first test case I hit a defined handler while in the second test case I am hitting some random handler so as to make that case fail.
The code is getting passed but every time the second test case is giving 500 as the response.
Below is the code of my test case.
func TestGetProviders(t *testing.T) {
type args struct {
path string
handler gin.HandlerFunc
}
tests := []struct {
name string
args args
want bool
}{
{
"First",
args{
"/api/v1/providers",
GetProviders,
},
true,
},
{
"Second",
args{
"/demo",
TheFunc,
},
false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
value := copyCodeGet(tt.args.path, tt.args.handler)
if len(value["response"]) > 0 {
statusCode, _ := strconv.Atoi(value["response"]["code"])
if val := statusCode == config.SuccessCode && value["response"]["message"] == config.SuccessMsg; val != tt.want {
t.Errorf("Error is:%v && Status code should be %v, was %d.", value, http.StatusOK, statusCode)
}
}
})
}
}