mockgen无法为测试文件内的接口生成Mock文件问题求助
问题解决:mockgen生成测试文件中接口的Mock失败
核心报错原因
- mockgen默认扫描非测试文件:你要生成Mock的
MyStructIntf接口定义在heap1_test.go(测试文件)里,mockgen默认只会查找不带_test.go后缀的非测试Go文件,所以无法识别到目标接口。 - 模块路径识别问题:当前
testfiles目录下没有非测试Go文件,导致mockgen无法正确解析vscodego/testfiles这个模块路径。
解决方法
方法一:规范代码结构(推荐)
把接口和业务结构体移到非测试文件中,这是Go项目的标准做法:
- 在
~/vscodego/testfiles目录下新建interfaces.go文件,写入以下内容:
package testfiles type MyStruct struct { age int Name string } func (m *MyStruct) getName() string { return m.Name } type MyStructIntf interface { getName() string }
- 修改
heap1_test.go,只保留测试逻辑:
package testfiles import "testing" func TestHeap1(t *testing.T) { }
- 执行生成命令(在项目根目录
~/vscodego下运行):
mockgen --build_flags=--mod=mod vscodego/testfiles MyStructIntf > testfiles/mock_mystructintf.go
方法二:直接指定测试文件生成(不推荐)
如果非要在测试文件里生成Mock,可以用-source参数指定目标测试文件,在~/vscodego/testfiles目录下执行:
mockgen --build_flags=--mod=mod -source=heap1_test.go MyStructIntf > mock_mystructintf.go
内容的提问来源于stack exchange,提问作者curiousengineer
相关产品推荐
相关产品推荐

