http test golang
library for http testing for gin framework
https://github.com/restuwahyu13/go-supertest
http test golang
library for http testing for gin framework
https://github.com/restuwahyu13/go-supertest
golang http testing
// main.go
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
)
type Response struct {
Message string `json:"message"`
}
func GetRequest(rw http.ResponseWriter, req *http.Request) {
rw.Header().Add("Content-Type", "application/json")
if req.Method == "GET" && req.URL.Path == "/get" {
data := Response{Message: "Hello World From - GET"}
json, _ := json.Marshal(data)
fmt.Fprint(rw, string(json))
} else {
data := Response{Message: "Bad Request"}
json, _ := json.Marshal(data)
fmt.Fprint(rw, string(json))
}
}
func main() {
http.HandleFunc("/get", GetRequest)
log.Fatal(http.ListenAndServe(":8000", nil))
}
// main_test.go
package main
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
)
func TestGetRequest(t *testing.T) {
var response Response
assert := assert.New(t)
rq := httptest.NewRequest("GET", "/get", nil)
rr := httptest.NewRecorder()
handler := http.HandlerFunc(GetRequest)
handler.ServeHTTP(rr, rq)
err := json.Unmarshal([]byte(rr.Body.String()), &response)
if err != nil {
t.Error("Parse JSON Data Error")
}
if response.Message == "Bad Request" {
t.Error("Request Failed")
}
assert.Equal(rr.Code, 200)
assert.Equal(response.Message, "Hello World From - GET")
}
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us