Last active
March 24, 2020 15:24
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.