I am working on learning go with a simple program that is doing some file reading and am working on adding unit testing to my program. I have ran into an issue/question while doing this. I want to unit test the function below and my question is that the function takes a name of the file which is then opened and processed. During testing I do not want to actually pass it a real file. I am wondering is this something I can somehow mock so that I can just pass it a "fake" file and have it process that instead? Thanks!
func openAndReadFile(fileName string) [][]string {
file, err := os.Open(fileName)
if err != nil {
fmt.Printf("Failed to read file: %s", fileName)
}
r := csv.NewReader(file)
lines, err := r.ReadAll()
if err != nil {
log.Fatal(err)
}
return lines
}
The function you have shown is dominated by interactions: Interactions with the file system and interactions with the csv reader. To be sure that these interactions work nicely you will later anyway have to do some integration-testing against the file system and the csv reader. Think about which bugs you are hoping to find, and you will see that bugs are more likely on the interaction level: Is the order of file,err correct, or should it be the other way around? Is nil really the value indicating no error? Do you have to give more arguments to Open? etc.
Therefore, I would not concentrate on unit-testing this function. However, this function is a good candidate to be mocked to make unit-testing the surrounding code easier. Thus, mock openAndReadFile
to unit-test the surrounding code, and test openAndReadFile
using integration-testing.
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