unit-testing - Golang如何使用接收器对私有方法进行单元测试
问题描述
在 Go 中,如何使用接收器对私有方法进行单元测试?例如,如何对代码段进行单元测试,如下所示。
如果启动一个实例srv
,则isShare
通过实例的句柄隐藏。所以在测试代码中不能调用isShare
.
搜索并阅读了一些帖子,但它们都是关于未指定接收者的私有函数。
package service
func (s *srv) isShare(id string) ( bool, error) {
record := s.db.Get(id)
if record != nil {
return true, nil
}
return false, errors.New("record not found.")
}
一个额外的问题可能是,如果在实例中srv
实例化了一个 DB 类型字段,那么在单元测试中,如何将模拟 DB 字段绑定到srv
而不是真正的 DB 类型?
解决方案
You can call un-exported methods from the same package, so just add your tests to the package. It's very common (basically the norm) for tests files to be in the same package as the code they are testing.
推荐阅读
- r - 如何使用字符串作为函数的正式形式运行函数?
- azure - Azure 存储队列最大并发客户端数
- sql - 从查询中获取 2019 年结果
- django - 调试工具栏 django 未执行
- c# - 传入字典的模型项在我的代码中属于类型错误
- javascript - 尝试将事件从其组件之一传播到自定义 HTML 元素会抛出
- node.js - 如何在nodejs中使用openssl生成公钥/私钥对?
- c# - 将事件的订阅者复制到派生对象
- angular - Angular6 - 如何使用服务渲染组件
- android - java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“android.net.Uri android.content.Intent.getData()”