我在代码中使用dutchcoders/goftp,出于单元测试的目的,我需要对其进行模拟。
这个组件没有接口,也没有可用的模拟,所以我尝试创建一些组件:
在goftp/ftp.go
中,
我添加了界面:
type FTPIface interface {
Close() error
Walk(path string, walkFn WalkFunc) (err error)
Rename(from string, to string) (err error)
Login(username string, password string) (err error)
}
现在,我可以模拟除Connect()
以外的所有其他方法,因为connect没有接收者。
您这样使用:
if client, err = goftp.Connect(Host); err != nil {
return nil, err
}
因此,我尝试将其更改为能够模拟它:
func NewMyFTP(ftpIface goftp.FTPIface, host, user, password, name string) (*MyFTP, error)
{
if Client, err = ftpIface.Connect(Host); err != nil {
return nil, err
}
if err = Client.Login(user, password); err != nil {
return nil, err
}
}
并在界面定义中添加了Connect()
Connect(addr string) (*FTP, error)
我可以模拟连接,但是它将返回一个FTP对象,而我将无法模拟Login()
那我该怎么办?