Skip to content

Instantly share code, notes, and snippets.

@sonya
sonya / contrived_scenario.go
Last active November 4, 2021 02:45
http request mocking code samples
type ValueHolder struct {
Value string
}
func GetFixedValue(baseURL string) (string, error) {
url := fmt.Sprintf("%s/fixedvalue", baseURL)
request, _ := http.NewRequest(http.MethodGet, url, nil)
request.Header.Add("Accept", "application/json")
client := &http.Client{}
@sonya
sonya / gock_test.go
Created November 4, 2021 02:42
http request mocking code samples
func TestGetFixedValue(t *testing.T) {
defer gock.Off()
gock.New("https://example.com/fixedvalue").
MatchHeader("Accept", "application/json").
Get("/").
Reply(200).
JSON(map[string]string{"value": "fixed"})
value, _ := GetFixedValue("https://example.com")
@sonya
sonya / httpmock_test.go
Created November 4, 2021 02:42
http request mocking code samples
func TestGetFixedValue(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
httpmock.RegisterResponder("GET", "https://example.com/fixedvalue",
func(req *http.Request) (*http.Response, error) {
if req.Header.Get("Accept") != "application/json" {
t.Errorf("Expected Accept: application/json header, got: %s", req.Header.Get("Accept"))
}
resp, err := httpmock.NewJsonResponse(200, map[string]interface{}{
@sonya
sonya / httptest_test.go
Created November 4, 2021 02:43
http request mocking code samples
func TestGetFixedValue(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/fixedvalue" {
t.Errorf("Expected to request '/fixedvalue', got: %s", r.URL.Path)
}
if r.Header.Get("Accept") != "application/json" {
t.Errorf("Expected Accept: application/json header, got: %s", r.Header.Get("Accept"))
}
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"value":"fixed"}`))
@sonya
sonya / interface_approach.go
Created November 4, 2021 02:44
http request mocking code samples
type HTTPClient interface {
Do(req *http.Request) (*http.Response, error)
}
var (
Client HTTPClient
)
func init() {
Client = &http.Client{}
@sonya
sonya / interface_approach_integration_test.go
Created November 4, 2021 02:44
http request mocking code samples
func TestGetFixedValue(t *testing.T) {
value, err := mockbyhand.GetFixedValue("http://localhost:8080")
if err != nil {
t.Error(err)
}
if value != "actualvalue" {
t.Errorf("Expected 'actualvalue', got %s", value)
}
}
@sonya
sonya / interface_approach_test.go
Created November 4, 2021 02:45
http request mocking code samples
func TestGetFixedValue(t *testing.T) {
Client = &MockClient{
DoFunc: func(req *http.Request) (*http.Response, error) {
if req.URL.Path != "/fixedvalue" {
t.Errorf("Expected to request '/fixedvalue', got: %s", req.URL.Path)
}
if req.Header.Get("Accept") != "application/json" {
t.Errorf("Expected Accept: application/json header, got: %s", req.Header.Get("Accept"))
}