如何模拟接口实现

问题描述 投票:-2回答:1

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进行模拟实现(因为它需要我们实现fun2fun3以及Foo中没有使用的)?

有什么方法可以为Foo编写测试,其中我们只需要编写fun1的模拟实现而不是fun2fun3

另外,在Go中测试这种接口使用的理想方法是什么?

go testing mocking
1个回答
2
投票

你必须实现所有方法。接口是合同,您需要履行此合同。

如果您确定不会调用fun2fun3方法,那么通常意味着您的接口合约太宽。在这种情况下,考虑将fun1提取到专用接口。

© www.soinside.com 2019 - 2024. All rights reserved.