【问题标题】:Is there a way to mock a type assertion using gomock?有没有办法使用 gomock 模拟类型断言?
【发布时间】:2021-11-18 10:14:56
【问题描述】:

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

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

例如。代码sn-p:

// 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:
    ...
  }
}

【问题讨论】:

  • 能分享一下实现逻辑的函数的sn-p吗?
  • 没问题,让我编辑帖子!

标签: go testing gomock


【解决方案1】:

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

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

【讨论】:

  • 谢谢@beam,想知道除了传入测试数据之外是否还有其他方法,我猜没有。干杯
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-31
  • 2017-08-21
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多