Skip to content

Instantly share code, notes, and snippets.

@vsouza
Created April 13, 2023 19:34
Show Gist options
  • Save vsouza/891c70c2e3ceec24f745fd7452c5b660 to your computer and use it in GitHub Desktop.
Save vsouza/891c70c2e3ceec24f745fd7452c5b660 to your computer and use it in GitHub Desktop.
Mocking HTTP Request inside methods in Golang
package main
import (
"io"
"log"
"net/http"
)
type httpClient interface {
Get(string) (*http.Response, error)
}
type myStruct struct {
httpClient httpClient
}
// example method
func (m myStruct) getExample() ([]byte, error) {
resp, err := m.httpClient.Get("https://example.com")
if err != nil {
return nil, err
}
defer resp.Body.Close()
return io.ReadAll(resp.Body)
}
func main() {
log.Print("inicializando")
}
package main
import (
"fmt"
"io"
"net/http"
"strings"
"testing"
)
func TestOne(t *testing.T) {
client := new(mockedClient)
s := myStruct{httpClient: client}
client.On(
"Get", "https://example.com",
).Return(
&http.Response{
StatusCode: 200,
Body: io.NopCloser(strings.NewReader(`{"userId": 2,"id": 2,"title": "test title2","body": "test body2"}`)),
}, nil,
)
body, err := s.getExample()
if err != nil {
println(err.Error())
}
fmt.Println(body)
}
package main
import (
"net/http"
"github.com/stretchr/testify/mock"
)
type mockedClient struct {
mock.Mock
}
func (m mockedClient) Get(url string) (*http.Response, error) {
args := m.Called(url)
if args.Get(0) == nil {
return nil, args.Error(1)
} else {
return args.Get(0).(*http.Response), args.Error(1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment