Golang - Testing with filesystem and reaching 100%

前端 未结 1 546
你的背包
你的背包 2021-01-20 04:37

I\'m trying to test one of my package to reach 100%. However, I can\'t find how I can do this without being \"against the system\" (functions pointers, etc.).

I trie

相关标签:
1条回答
  • 2021-01-20 04:53

    I attempted to do same thing, just to try it. I achieved it by referencing all system file calls as interfaces and having method accept an interface. Then if no interface was provided the system method was used. I am brand new to Go, so I'm not sure if it violates best practices or not.

    import "io/ioutil"
    
    
    type ReadFile func (string) ([]byte, error)
    
    
    type FileLoader interface {
        LoadPath(path string) []byte
    }
    
    // Initializes a LocalFileSystemLoader with default ioutil.ReadFile
    // as the method to read file.  Optionally allows caller to provide
    // their own ReadFile for testing.
    func NewLocalFileSystemLoader(rffn ReadFile) *localFileSystemLoader{
        var rf ReadFile = ioutil.ReadFile
    
        if rffn != nil {
            rf = rffn
        }
        return &localFileSystemLoader{
            ReadFileFn: rf}
    }
    
    type localFileSystemLoader struct {
        ReadFileFn ReadFile
    }
    
    func (lfsl *localFileSystemLoader) LoadPath(path string) []byte {
        dat, err := lfsl.ReadFileFn(path)
        if err != nil {
            panic(err)
        }
    
        return dat
    }
    
    0 讨论(0)
提交回复
热议问题