dourong4031 2017-04-14 10:41
浏览 2

初始化功能中断单元测试

In the package I want to test, I have an init function that loads the configuration file containing some stuff I want to use to run my application. However, I don't want to trigger this init function while running my unit tests.

Is there any way for skipping or preventing this init function to be called during the unit tests?

Some snippets to illustrate the question:

func init() {
    var err error // Necessary to prevent config variable shadowing
    config, err = loadConfig("./client/config.yml")
    if err != nil {
        log.Fatal(err)
    }
}

func loadConfig(filepath string) (*Config, error) {
    viper.SetConfigFile(filepath)
    if err := viper.ReadInConfig(); err != nil {
        return nil, fmt.Errorf("Error loading config file: %s", err)
    }
  (...)
}

// New returns a Config value(!)
func New() Config {
    return *config
}

A test case:

func TestNew(t *testing.T) {
    expected := &Config{}
    observed := New()
    if !reflect.DeepEqual(observed, expected) {
        t.Errorf("observed %+v. expecting %+v
", observed, expected)
    }
}
  • 写回答

1条回答 默认 最新

  • dongtanzhu5417 2017-04-14 11:25
    关注

    I'm not sure whether there's a nicer way of doing this, but if you consider the fact that package-level variables are initialized before the init func is run you can use a flag to tell you whether you're running tests or not.

    var _testing = false
    
    func init() {
        if _testing {
            return
        }
    
        var err error // Necessary to prevent config variable shadowing
        config, err = loadConfig("./client/config.yml")
        if err != nil {
            log.Fatal(err)
        }
    }
    
    // ...
    

    And in your test file you could do something like this:

    // not nice but works
    var _ = (func() interface{} {
        _testing = true
        return nil
    }())
    
    func TestNew(t *testing.T) {
        expected := &Config{}
        observed := New()
        if !reflect.DeepEqual(observed, expected) {
            t.Errorf("observed %+v. expecting %+v
    ", observed, expected)
        }
    }
    

    You can read more on the initialization order here: https://golang.org/ref/spec#Program_initialization_and_execution

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题