go - 有没有办法使用 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:
...
}
}
解决方案
gomock
为接口生成新的实现。(对于接口Foo
实现是MockFoo
结构)。在您的场景中,此类模拟仅涵盖default
案例。
最简单的处理方法DoSomething(i foo)
是通过具体实现(基于您的场景的测试数据)
推荐阅读
- javascript - Kendo PopupWindow 如何将内容设置为 jquery 帖子?
- firefox - AWSALB、AWSALBCORS cookie 和 Firefox
- vue.js - Vue Router:根据用户角色加载路由
- javascript - JavaScript 的 %[flag][width] 等价物(C 和 Java 格式说明符)
- unit-testing - 无法模拟方法 - Mockito - Kotlin
- python - 有没有办法在 OpenGL 上显示一个 pygame 窗口?
- javascript - 如何将数组数据从控制器发送到刀片并访问 javascript 变量中的数据
- html - 当元素不在 1 行时,为什么 HTML 元素之间的空格分隔符不存在?
- react-native - 关闭 React Navigation 堆栈卡片时修改卡片样式
- hikaricp - JDBC连接被取出并返回到JDBC连接池时如何拦截?