mardi 22 décembre 2020

Get access to one package's `export_test.go` variables from another test package [duplicate]

In my project I have the code split up in packages, one of them named config being used by the main package.

One of the things the config package does is loading configuration file stored in some default location. However, when testing the main package I want config to load another file.

Currently, my code is structured like so:

// config/config.go
package config

var getConfigPath = func() (string, error) {
   ...
}

func Load() (error) {
   path, err := getConfigPath()
   ...
}


// config/export_test.go
package config

// "export" getConfigPath so that it can be mocked in tests
var GetConfigPath = getConfigPath
// main_test.go
package main_test

import ".../config"

func loadTestConfig() {
  // Trying to mock `config.GetConfigPath` here, it doesn't work. `config.GetConfigPath` is undefined
  config.GetConfigPath = func() (string, error) {
    ...
  }
}

func TestFoo(...) { ... }

However, if I create a separate _test package in config (i.e. package config_test), there I can get access and modify config.GetConfigPath:

// config/config_test.go
package config_test

import ".../config"

func loadTestConfig() {
  // This works
  config.GetConfigPath = func() (string, error) {
    ...
  }
}

Is there any workaround to get access to one test package variables in from another test package? Or is there another way to mock a private function from one package in another package's test?

Aucun commentaire:

Enregistrer un commentaire