Skip to content

Instantly share code, notes, and snippets.

@anitsh
Last active March 24, 2020 15:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anitsh/23c77b6a6b5fd12c0edeb16a628a3aa7 to your computer and use it in GitHub Desktop.
Save anitsh/23c77b6a6b5fd12c0edeb16a628a3aa7 to your computer and use it in GitHub Desktop.
Fundamental: A test is not a unit test if it touches the file system. A NOT TO DO EXAMPLE in Go.
package myfile
// openFileInPath Opens a file in the fileLocation path.
// It return the file pointer or any error encountered.
func openFile(fileLocation string) (*os.File, error) {
filePointer, err := os.Open(fileLocation)
if err != nil {
return nil, err
}
return filePointer, nil
}
package myfile
func TestOpenFileFileExistsInPath(t *testing.T) {
licenseFile := "/tmp/test-file.txt"
licenceFileContent := []byte("This is the key. Must ignore other lines.\nMust be ignored.\n Must be ignored.\n")
err := ioutil.WriteFile(licenseFile, licenceFileContent, 0400)
if err != nil {
t.Errorf(err.Error())
}
t.Run("", func(t *testing.T) {
filePointer, _ := openFile(licenseFile)
filePointerType := fmt.Sprint(reflect.TypeOf(filePointer))
if strings.Compare(filePointerType, "*os.File") != 0 {
t.Fatal("Error while reading file in the path")
}
kindOfFile := reflect.ValueOf(filePointer).Kind()
if kindOfFile != reflect.Ptr {
t.Fatal("Error while reading file in the path")
}
})
err = os.Remove(licenseFile)
if err != nil {
fmt.Println(err)
return
}
}
@anitsh
Copy link
Author

anitsh commented Mar 24, 2020

The better way to do is in case of need to do would be with Mocks.
Mocks are what we are talking about here: objects pre-programmed with expectations which form a specification of the calls they are expected to receive.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment