如何模拟接口实现

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())
    }
}

While writing tests for Foo, is it necessary to do a mock implementation of the interface MyInterface (as it requires us to implement fun2 and fun3 as well which are not being used in Foo)?

Is there any way in which we can write tests for Foo wherein we just need to write the mock implementation of fun1 and not for fun2 and fun3?

Also, what's the ideal way to test such use of interfaces in Go?

You have to implement all the methods. Interface is a contract and you need to fulfill this contract.

If you're sure that fun2 and fun3 methods will not be called, then it usually means that your interface contract is too wide. Consider extracting fun1 into dedicated interface in such case.