Created
April 13, 2023 19:34
-
-
Save vsouza/891c70c2e3ceec24f745fd7452c5b660 to your computer and use it in GitHub Desktop.
Mocking HTTP Request inside methods in Golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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