I want to write test cases for my api like: database query fail,error in code,response error etc.
So I have created one file called controller_test.go in controllers folder.
here is my code:
package controllers
import (
"net/http"
"testing"
"net/http/httptest"
)
func (imc ImessageSoundController) TestHealthCheckHandler(t *testing.T) {
req, err := http.NewRequest("GET","sound/imessage_sound", nil)
if err != nil {
t.Fatal(err)
}
rr := httptest.NewRecorder()
handler := http.HandlerFunc(imc.ImessageSound)
handler.ServeHTTP(rr, req)
if status := rr.Code; status != http.StatusOK {
t.Errorf("handler returned wrong status code: got %v want %v",
status, http.StatusOK)
}
}
My api logic is written in code.go in controllers folder. here is my code:
package controllers
import (
//required packages
)
type (
ImessageSoundController struct {
session *sql.DB
}
)
func NewImessageSoundController(s *sql.DB) *ImessageSoundController {
return &ImessageSoundController{s}
}
func (imc ImessageSoundController) ImessageSound(w http.ResponseWriter, r *http.Request) {
//Code logic
}
I am getting this output for above case:
testing: warning: no tests to run
PASS
ok tingtong2.1/controllers 0.004s
As I am new to this I am not able to find reason for this error.
A test should be a function, not a method. Just make it:
func TestHealthCheckHandler(t *testing.T) {
...
}
Good luck!