“Test de Golang HTTP” Réponses codées

Test de Golang HTTP

// 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")
}
Restu Wahyu Saputra

HTTP Test Golang

library for http testing for gin framework

https://github.com/restuwahyu13/go-supertest
Restu Wahyu Saputra

Réponses similaires à “Test de Golang HTTP”

Questions similaires à “Test de Golang HTTP”

Plus de réponses similaires à “Test de Golang HTTP” dans Go

Parcourir les réponses de code populaires par langue

Parcourir d'autres langages de code