In the Golang project under test, there's a method that loads a JSON config file into a variable. Its code is like this:
// Load the JSON config file
func Load(configFile string, outputObj interface{}) *errors.ErrorSt {
var err error
// Read the config file
jsonBytes, err := ioutil.ReadFile(configFile)
if err != nil {
fmt.Println(err.Error())
return errors.File().AddDetails(err.Error())
}
// Parse the config
if err := json.Unmarshal(jsonBytes, outputObj); err != nil {
return errors.JSON().AddDetails("Could not parse" + configFile + ": " + err.Error())
}
return nil
}
I wish to test it but I don't know if I should create fake JSON file for the test cases, or just mock the whole function. My Java background has me leaning towards the latter.
Exploring that, I found the testify framework I'm using has a package for mocking methods, but what I'm attempting to mock doesn't belong to interfaces (the pitfalls of non-OOP languages!!)
There's a couple ways to do it. It's certainly not unusual to have a sample data file to test loading & parsing a file (you'll find this in places in the standard library). It's also a pretty common practice for a function like this to take in an io.Reader rather than a file path, so that in testing you can just pass in e.g. a bytes.Reader to effectively "mock" the file while testing everything else. Which method to use (or both, if you choose) depends on your use case and design objectives; switching to an io.Reader gives you more flexibility, but only you know if that flexibility has any value in context. If not, just keep a test file along with your tests and read that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With