Hello, I am trying to test a file open error operation with fstest.
The way that I tried seems extremely large and I think I am missing some type of operation. https://go.dev/play/p/WKEBVh3pZmq (I posted the code here)
Does someone know how I could write a simple unit test for this use case?
#fstest for invalid file
16 messages · Page 1 of 1 (latest)
So the purpose of this program is to get the keys from a json file? is that right
yes it is part of a larger program but I am trying to test the io.ReadAll
Why do you want to test io.ReadAll?
It shows as not covered in the test cases
Therefore I was asked to also provide a testcase for the code containing io.ReadAll
https://go.dev/play/p/PuWAI3hx1Rr
For reference this is the whole getkeys function
You mean coverage for the code inside the if-statement?
yes exactly
I am rather new to code testing in go 😅
You can't make it fail unless the system is completely broken and can't read things
Or you need to mock the fs.FS where reading fails
Also, instead of reading all of it and then unmarshal, you can do this:
func getKeys(fileSystem fs.FS) (CiscoKey, error) {
file, err := fileSystem.Open("key.json")
if err != nil {
log.Error().Err(err).Msg("Could not open key.json File")
return nil, err
}
defer file.Close()
decoder := json.NewDecoder(file)
var ciscoKey CiscoKey
if err = decoder.Decode(&ciscoKey); err != nil {
log.Error().Err(err).Msg("Error while unmarshal of JSON")
return nil, err
}
return ciscoKey, nil
}
And to test it, you need to mock fs.FS.
Rudimentary mocked fs.FS.
It will fail to open if the file doesn't exist in the map. Read will fail with io.UnexpectedEOF if the data is nil, so you can test both missing file and failed read.
However, ask yourself, do you really want to get coverage for that part?
Thank you! I tried and it works like a charm! 😄