1

GoMock

 2 years ago
source link: https://linuxsuren.github.io/blog/language/golang/gmock/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

GoMock

GoMock

GoMock 是 Go 语言的 Mock 框架。它可以很很好地和 Go 内置的 testing 包集成。

你只要安装了 Go 就可以通过下面的命令来安装 gomockmockgen 工具。

go get github.com/golang/mock/gomock
go install github.com/golang/mock/mockgen

编写接口(测试用)

codes/golang/gmock/foo.go
package main

// Foo no-sense interface demo
type Foo interface {
	Max(a, b int) int
}

func main() {}
原文件

生成 Mock 接口

执行命令 mockgen --source=foo.go --destination foo-mock.go

codes/golang/gmock/foo_test.go
package main

import (
	"testing"

	"./mock_main"

	"github.com/golang/mock/gomock"
)

func TestFoo(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()
	expect := 2

	m := mock_main.NewMockFoo(ctrl)
	m.EXPECT().Max(1, 2).Return(expect)

	if m.Max(1, 2) != expect {
		t.Errorf("max result is wrong, should be %d\n", expect)
	}
}
原文件

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK