首页 > 解决方案 > 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 类型?

标签: unit-testinggotestng

解决方案


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.


推荐阅读