【问题标题】:How to mock interface implementation如何模拟接口实现
【发布时间】: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 进行模拟实现(因为它需要我们实现fun2fun3 以及Foo 中没有使用的fun3 )?

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

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

【问题讨论】:

  • 你可以通过将接口嵌入到mock中来省略你不需要的方法的mock实现。请记住,如果被测代码中的任何内容调用未实现的方法,它将导致panicplay.golang.org/p/wSjz5SoEHyv
  • 你想测试什么? Foo?然后你不需要mock任何东西,你只需要传递一个实现MyInterface的值。如果您已经有类似MyInterfaceImplementation 的实现,只需使用它即可。
  • 还要注意,如果Foo()只使用func1()方法,那么它不应该期望一个实现MyInterface的值,只有一个具有单个func1()方法的接口,甚至更好:它应该只期望一个函数值。

标签: go testing mocking


【解决方案1】:

你必须实现所有的方法。接口是一个契约,你需要履行这个契约。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-19
    • 2013-04-01
    • 2021-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多