1 使用github.com/vektra/mockery
https://github.com/vektra/mockery
目录结构:
.
├── mock_stringer
│ └── Stringer.go
├── stringer.go
└── stringer_test.go
1 directory, 3 files
stringer.go
go:generate
所在注释行不能有空格,只要执行go generate
即可自动生成
package stringer
//go:generate mockery -outpkg mock_stringer -output ./mock_stringer -name Stringer
type Stringer interface {
String(int) string
}
stringer_test.go
package stringer
import (
"testing"
"github.com/wncbb/mockery_pg/stringer/mock_stringer"
)
func TestStringer(t *testing.T) {
m := mock_stringer.Stringer{}
m.On("String", 12).Return("ThisIs12")
t.Logf("m.String(12): %s", m.String(12))
}
2 使用github.com/golang/mock/gomock
https://blog.codecentric.de/en/2017/08/gomock-tutorial/
目录结构:
.
└── stringer
├── mock_stringer
│ └── mock_stringer.go
├── stringer.go
└── stringer_test.go
2 directories, 3 files
stringer.go
go:generate
所在注释行不能有空格,只要执行go generate
即可自动生成
package stringer
//go:generate mockgen -destination=./mock_stringer/mock_stringer.go -package=mock_stringer github.com/wncbb/gomock_pg/stringer Stringer
type Stringer interface {
String(int) string
}
stringer_test.go
package stringer
import (
"testing"
"github.com/golang/mock/gomock"
"github.com/wncbb/gomock_pg/stringer/mock_stringer"
)
func TestStringer(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
m := mock_stringer.NewMockStringer(ctrl)
m.EXPECT().String(12).Return("ThisIs12").Times(1)
t.Logf("m.String(12): %s", m.String(12))
}
有疑问加站长微信联系(非本文作者)