go - Init function breaking unit tests -
in package want test, have init function loads configuration file containing stuff want use run application. however, don't want trigger init function while running unit tests.
is there way skipping or preventing init function called during unit tests?
some snippets illustrate question:
func init() { var err error // necessary 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 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\n", observed, expected) } }
i'm not sure whether there's nicer way of doing this, if consider fact package-level variables initialized before init
func run can use flag tell whether you're running tests or not.
var _testing = false func init() { if _testing { return } var err error // necessary prevent config variable shadowing config, err = loadconfig("./client/config.yml") if err != nil { log.fatal(err) } } // ...
and in test file this:
// not nice 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\n", observed, expected) } }
you can read more on initialization order here: https://golang.org/ref/spec#program_initialization_and_execution
Comments
Post a Comment