Golang: unit testing fuction depenent on io.File.Write()

  • reposted from stackoverflow as per advice from there

Hеllo, fellow Gophers!

Learning how to write unit tests and got stuck. Please, don’t beat me up, cause I am new to this. I’ve googled and read a lot, but I still couldn’t come up with a proper solution.
The exercise is to write a unit test for a function I wrote:

Filecopy(pathfrom, pathto string, limit, offset int64) error

The simplified function will look like this

source, err := os.Open(pathfrom)
	destination, err := os.Create(pathto)
	buf := make([]byte, *buffersize)
	for {
		n, err := source.Read(buf)
		if err != nil && err != io.EOF {
			return err
		if _, err := destination.Write(buf[pos:n]); err != nil {
			return err
			if n == 0 {

Now I have to unit test it. And it’s not going well. There are two ways I could test it:

  1. Provide it a real temp file with a predetermined contents, so the test function would know what to expect after the execution. Should work, but I read this option is NOT the way to unit test properly as it touches the FS.
  2. Use fake FS. I’ve tried testing files generated by mapfs and afero, but no luck, my function doesn’t work with it (it works with real files though), either I am doing something wrong.

Please tell me how to unit test my function properly. Any help will be appreciated.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.