Using package level variables in go test files

1.3k Views Asked by At

I am trying to write a unit test for a file that is like this

//file1.go
var (
    fileName = "/path/to/original/file.json"
)

func DoSomething(){
    // Read <fileName> and do some stuff
}

But for unit testing, I would like to use /path/to/dummy/file.json to be used by DoSomething() file1_test.go will be under the same package as file.go What would be the correct approach for writing test cases for this function?

Will it be a good idea to modify fileName variable to /path/to/dummy/file.json ? or Should we modify the file1.go to make it suitable for testing?

Is this the standard to make these kind of values configurable so that they can modified during unit testing e.g. file name in this case or we should modify our function so that it can work with byte stream data directly so during testing testing we can feed dummy data directly?

1

There are 1 best solutions below

0
On BEST ANSWER

Use Config/Settings structs. In production, it's better to use YAML to hold configuration values

type Config struct{FileName string}

In main.go

var conf Config
func main(){
   conf = LoadConfigFromYaml()
   DoSomething()
}

func DoSomething(){
// Read <fileName> from conf.FileName
}

In main_test.go

func TestSomething(t *testing.T){
   conf = Config{FileName: "/path/to/dummy/file.json"}
   DoSomething()
}

It also allows you to set different config for each test.

A better approach will be to create a library that accepts Config at initialisation and inject config from main and from the test and avoid using main package variable.