【问题标题】:Gomock cannot use type map[string]*mockFoo as map[string]fooGomock 不能使用类型 map[string]*mockFoo 作为 map[string]foo
【发布时间】:2021-11-27 04:45:26
【问题描述】:

我正在使用 gomock,并且我希望测试这段示例代码。

type StructA struct {
  client map[string]Foo
}

type Foo interface {
  foo.methodFoo() string
}

func (a *structA) MethodA(name string) string {
  client := a.client[name]
  return client.methodFoo()
  
}

在我的测试中,我为 foo 生成了一个模拟,称为 mockFoo。使用 mockgen v1.6.0 生成接口 foo 的 mock。

我的测试代码为:

func Test_MethodA(t *testing.T) {
  type fields struct {
    client map[string]*mockFoo
  }
  tests := []struct {
    fields fields
    want   string
  }
  { 
     // test cases
  }
  for _, tt := range tests {
    t.Run(tt.name, func(t *testing.T) {
      a := &StructA {
        client: tt.fields.client //this has an error, saying that we cannot use map[string]*mockFoo as the type map[string]foo
      }
      ...
    })
  }
}

TLDR是map[string]*mockFoo不能作为map[string]Foo的类型。

var foo1 Foo
var mockFoo1 *mockFoo
foo1 = mockFoo1 // no problem

var fooMap map[string]Foo
var mockFooMap map[string]*mockFoo
fooMap = mockFooMap // problematic

我可以知道我在这里做错了什么还是这是预期的行为?谢谢。

【问题讨论】:

    标签: go testing gomock


    【解决方案1】:

    根据您的描述,Foo 是一个接口,*mockFoo 实现了Foo 接口。因此,只要需要Foo,您就可以使用*mockFoo

    map[string]Foo 类型与map[string]*mockFoo 类型不同。两者都是具体类型(它们不是接口),所以你不能用一个代替另一个。

    但是,您可以使用 map[string]Foo,并将 *mockFoo 值放入该映射中,据我从您的代码中可以看出,这就是您应该做的。将地图声明为map[string]Foo,并在其中使用*mockFoo 值。如果您需要将映射的值引用为*mockFoo,您可以对映射值进行type-assert 以获得*mockFoo 的值,即:

    fooMap=map[string]Foo{}
    fooMap["key"]=mockFoo1
    ...
    value:=foomap["key"].(*mockFoo)
    

    【讨论】:

      猜你喜欢
      • 2022-11-10
      • 1970-01-01
      • 1970-01-01
      • 2020-01-27
      • 2018-03-22
      • 2019-12-06
      • 2019-09-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多