为何mockgen会生成文件中全部接口?如何仅生成指定接口?
解决mockgen生成指定接口Mock的问题
你遇到的问题是因为mockgen在source模式下,直接在命令末尾添加接口名的写法不正确,导致工具没有识别到你要限定的接口,默认生成了文件中所有接口的Mock。
要仅生成指定接口的Mock,有两种正确的写法:
方法1:使用-interfaces参数明确指定接口
修改你的//go:generate注释,通过-interfaces参数指定要生成Mock的接口:
//go:generate mockgen -source interfaces.go -destination mock-interfaces.go -package worker -interfaces Doer
如果需要同时生成多个特定接口,用逗号分隔接口名即可:
//go:generate mockgen -source interfaces.go -destination mock-interfaces.go -package worker -interfaces Doer,LazyThing
方法2:使用reflect模式(可选)
如果你更倾向于reflect模式,可以直接指定包路径和接口名,不过这种模式需要确保包能被Go模块识别:
//go:generate mockgen your/module/path/worker Doer -destination mock-interfaces.go -package worker
执行go generate后,就只会生成你指定的Doer接口的Mock实现了。
内容的提问来源于stack exchange,提问作者Yura
相关产品推荐
相关产品推荐

