Update lecture

This commit is contained in:
Fedor Korotkiy 2020-03-19 16:23:32 +03:00
parent dccd98c578
commit 20483034d0
5 changed files with 122 additions and 0 deletions

View file

@ -0,0 +1,11 @@
package example
//go:generate mockgen -package example -destination mock.go . Foo
type Foo interface {
Bar(x int) int
}
func SUT(f Foo) {
// ...
}

View file

@ -0,0 +1,25 @@
package example
import (
"testing"
gomock "github.com/golang/mock/gomock"
)
func TestFoo(t *testing.T) {
ctrl := gomock.NewController(t)
// Assert that Bar() is invoked.
defer ctrl.Finish()
m := NewMockFoo(ctrl)
// Asserts that the first and only call to Bar() is passed 99.
// Anything else will fail.
m.
EXPECT().
Bar(gomock.Eq(99)).
Return(101)
SUT(m)
}

View file

@ -0,0 +1,47 @@
// Code generated by MockGen. DO NOT EDIT.
// Source: gitlab.com/slon/shad-go/lectures/04-testing/gomock (interfaces: Foo)
// Package example is a generated GoMock package.
package example
import (
gomock "github.com/golang/mock/gomock"
reflect "reflect"
)
// MockFoo is a mock of Foo interface
type MockFoo struct {
ctrl *gomock.Controller
recorder *MockFooMockRecorder
}
// MockFooMockRecorder is the mock recorder for MockFoo
type MockFooMockRecorder struct {
mock *MockFoo
}
// NewMockFoo creates a new mock instance
func NewMockFoo(ctrl *gomock.Controller) *MockFoo {
mock := &MockFoo{ctrl: ctrl}
mock.recorder = &MockFooMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use
func (m *MockFoo) EXPECT() *MockFooMockRecorder {
return m.recorder
}
// Bar mocks base method
func (m *MockFoo) Bar(arg0 int) int {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Bar", arg0)
ret0, _ := ret[0].(int)
return ret0
}
// Bar indicates an expected call of Bar
func (mr *MockFooMockRecorder) Bar(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Bar", reflect.TypeOf((*MockFoo)(nil).Bar), arg0)
}

View file

@ -0,0 +1,26 @@
package main
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
)
func main() {
handler := func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "<html><body>Hello World!</body></html>")
}
req := httptest.NewRequest("GET", "http://example.com/foo", nil)
w := httptest.NewRecorder()
handler(w, req)
resp := w.Result()
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(resp.StatusCode)
fmt.Println(resp.Header.Get("Content-Type"))
fmt.Println(string(body))
}

View file

@ -486,4 +486,17 @@ Good example
.play mocks/mocks_test.go /func/,/^}/
* gomock
.play gomock/example.go
- Запуск `go`generate`.` создаст файл `mock.go`
- Хорошая идея - класть `mock`-и в отдельный пакет.
* gomock
.play gomock/example_test.go
* httptest
.play httptest/main.go /func/,/^}/