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
中没有使用的)?
有什么方法可以为Foo
编写测试,其中我们只需要编写fun1
的模拟实现而不是fun2
和fun3
?
另外,在Go中测试这种接口使用的理想方法是什么?
你必须实现所有方法。接口是合同,您需要履行此合同。
如果您确定不会调用fun2
和fun3
方法,那么通常意味着您的接口合约太宽。在这种情况下,考虑将fun1
提取到专用接口。