cpt*_*ino 5 unit-testing interface mocking go vsphere
我正在尝试创建一个简单的模拟器,用于使用VMware vSphere API客户端 - govmomi对单个代码进行单元测试- 但是我无法找到可用的模式.
客户端库的一个简单用例是检索vSphere集群的已安装许可证:
vclient, err := govmomi.NewClient(*vcurl, true)
if err != nil {
return err
}
lic, err := vclient.LicenseManager().ListLicenses()
NewClient()Client.LicenseManager()LicenseManager.ListLicenses()ListLicenses()LicenseManger
VCenterClientClientNewVCenter()
import (
"net/url"
"github.com/vmware/govmomi"
"github.com/vmware/govmomi/vim25/types"
)
type VCenterClient struct {
VCenterClientInterface
}
type VCenterClientInterface interface {
LicenseManager() LicenseManager
}
type LicenseManager interface {
ListLicenses() ([]types.LicenseManagerLicenseInfo, error)
}
type VCenterClientMock struct{}
type LicenseManagerMock struct{}
func (v *VCenterClientMock) LicenseManager() LicenseManager {
return LicenseManagerMock{}
}
func (l LicenseManagerMock) ListLicenses() ([]types.LicenseManagerLicenseInfo, error) {
return make([]types.LicenseManagerLicenseInfo, 0), nil
}
func NewVCenterClient(uri string, mock bool) *VCenterClient {
if mock {
return &VCenterClient{&VCenterClientMock{}}
}
vcurl, _ := url.Parse(uri)
vclient, _ := govmomi.NewClient(*vcurl, true)
return &VCenterClient{vclient}
}
govmomi.LicenseManager()govmomi.LicenseManagerVCenterClientInterface.LicenseManager()LicenseManager
在这种情况下,任何有关更好的设计模式或正确使用接口的帮助都将非常受欢迎.