Answers for "unit test http request golang"

Go
0

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")
}
Posted by: Guest on October-08-2021

Browse Popular Code Answers by Language