【发布时间】:2019-04-03 08:39:32
【问题描述】:
myinterface.go
type MyInterface interface {
fun1() string
fun2() int
fun3() bool
}
func Foo(mi MyInterface) string {
return mi.fun1()
}
myinterface_test.go
type MyInterfaceImplementation struct{}
func (mi MyInterfaceImplementation) fun1() string {
return "foobar"
}
func (mi MyInterfaceImplementation) fun2() int {
return int(100)
}
func (mi MyInterfaceImplementation) fun3() bool {
return false
}
func TestFoo(t *testing.T) {
mi := MyInterfaceImplementation{}
val := Foo(mi)
if val != "foobar" {
t.Errorf("Expected 'foobar', Got %s", mi.fun1())
}
}
在为Foo 编写测试时,是否有必要对接口MyInterface 进行模拟实现(因为它需要我们实现fun2 和fun3 以及Foo 中没有使用的fun3 )?
有什么方法可以为Foo 编写测试,其中我们只需要编写fun1 的模拟实现而不是fun2 和fun3?
另外,在 Go 中测试这种接口使用的理想方法是什么?
【问题讨论】:
-
你可以通过将接口嵌入到mock中来省略你不需要的方法的mock实现。请记住,如果被测代码中的任何内容调用未实现的方法,它将导致
panic。 play.golang.org/p/wSjz5SoEHyv -
你想测试什么?
Foo?然后你不需要mock任何东西,你只需要传递一个实现MyInterface的值。如果您已经有类似MyInterfaceImplementation的实现,只需使用它即可。 -
还要注意,如果
Foo()只使用func1()方法,那么它不应该期望一个实现MyInterface的值,只有一个具有单个func1()方法的接口,甚至更好:它应该只期望一个函数值。