dream890110 2016-06-11 17:29
浏览 80

Golang-使用文件系统进行测试并达到100%

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 tried to do something similar to this, but I can't reach 100% because of "real" functions :

var fs fileSystem = osFS{}

type fileSystem interface {
    Open(name string) (file, error)
    Stat(name string) (os.FileInfo, error)
}

type file interface {
    io.Closer
    io.Reader
    io.ReaderAt
    io.Seeker
    Stat() (os.FileInfo, error)
}

// osFS implements fileSystem using the local disk.
type osFS struct{}

func (osFS) Open(name string) (file, error)        { return os.Open(name) }
func (osFS) Stat(name string) (os.FileInfo, error) { return os.Stat(name) }

(From https://talks.golang.org/2012/10things.slide#8)

Does someone would have a suggestion ? :) Thanks !

  • 写回答

1条回答 默认 最新

  • dpmir1988 2016-06-12 17:42
    关注

    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
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)