需要文件的单元测试方法

I've the following function and I need to create a unit test for it

package main

import (
    "fmt"
    "io/ioutil"
    "os"
)

type Source struct {
    Path string
}

type fileReader interface {
    readOneFile() ([]byte, error)
}

func(s Source) readOneFile() ([]byte, error) {
    cwd, err := os.Getwd()
    file, err := ioutil.ReadFile(fmt.Sprintf("%s/file.txt", cwd))
    if err != nil {
        return nil, fmt.Errorf("erro reading file : %s", err.Error())
    }
    return file, err
}

The problem is that I use path to file in the method, what it the best practice in go to create a unit test for this kind of functions ?

Tests will run in the directory that contains the tests

So Getwd will give the path to that directory

The filename for test data in files in test directories should begin with underscore _

However, your program needs a file called "file.txt" . To support testing this filepath that does not start with _ create the file file.txt in (for example) /tmp, do a chdir to /tmp immediately before running the test and let the test pick up the file that was just made

For writing unit test you need to create a file within same package with fileName_test.go Suppose your file name read.go so your test file name should be read_test.go.

read_test.go

      package main

      import (
         "testing"
         "fmt"
      )

    func TestReadOneFile(t *testing.T) {
        var a Source
        f, err := a.readOneFile()
        if err != nil {
           t.Errorf("incorrect")
        } else {
            fmt.Println("passed")
        }
    }

Here you have to named your test function name with Test as prefix and need to import package testing.

After creating the unit test you can check the code coverage by running below two commands:

1. go test --coverprofile coverage.out
2. go tool cover -html=coverage.out