Hi there!
I needed to test a few requests I do in my API and then I will show to you how I did that.
First things first, you need to create an application and a file with routes:
main.go
package main
import (
"net/http"
"devto.com/v1/src/router"
)
func main() {
/// Start server with Routes
http.ListenAndServe(":3333", router.Routes())
}
router\router.go
package router
import (
"net/http"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
)
func Routes() *chi.Mux {
r := chi.NewRouter()
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
r.Get("/info", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte(":)"))
})
return r
}
Then we're gonna make our test for that request called info
.
tests\integration\info_test.go
package integration
import (
"net/http"
"net/http/httptest"
"testing"
"devto.com/v1/src/router"
)
func TestInfoRequest(t *testing.T) {
// Set up a new request.
req, err := http.NewRequest("GET", "/info", nil)
if err != nil {
t.Fatal(err)
}
newRecorder := httptest.NewRecorder()
router.Routes().ServeHTTP(newRecorder, req)
statusCode := 200
if newRecorder.Result().StatusCode != statusCode {
t.Errorf("TestInfoRequest() test returned an unexpected result: got %v want %v", newRecorder.Result().StatusCode, statusCode)
}
}
That's all! I hope it helps you to get your integration tests working.
Top comments (0)