首页 > 解决方案 > 有没有办法使用 gomock 模拟类型断言?

问题描述

我是 golang 的新手并Gomock用于测试。我已经为接口生成了模拟foo,但在我的代码中有一段使用的逻辑foo.(type)

我可以知道是否有办法模拟这个并返回我选择的类型?如果没有,那么做这件事的好方法是什么?谢谢!

例如。代码片段:

// assume structs A and B implements the interface `foo` 
type foo interface {...}
type A struct {...}
type B struct {...} 

func DoSomething(i foo) {
  // Is there a way to mock this type assertion for i here? 
  switch currentType := i.(type) {
  case *A: 
    ...
  case *B:
    ...
  default:
    ...
  }
}

标签: gotestinggomock

解决方案


gomock为接口生成新的实现。(对于接口Foo实现是MockFoo结构)。在您的场景中,此类模拟仅涵盖default案例。

最简单的处理方法DoSomething(i foo)是通过具体实现(基于您的场景的测试数据)


推荐阅读