由于外部库不公开接口(因此不是可模拟的),而仅公开纯函数,因此我很难在Go中编写单元测试。即使像Google这样的大公司也没有,所以我想知道我的方法是否足够好。库interface不是提供s而不是仅提供函数的包以便用户模拟它们的好习惯吗?
到目前为止,我想出的解决方案是将这些包与接口的实现包装在一起,但这似乎工作量太大。
我举一个例子。我的功能可能看起来像这样
func AnyFunction() error {
sess := session.Get("blabla")
// logic in here...
}
Run Code Online (Sandbox Code Playgroud)
其中session是一个导入的包,返回struct。我不能嘲笑包裹session。对于这种情况,我将编写一个SessionInterface带有内部调用session的实现。
例如:
type SessionInterface interface {
Get(s string) Session
}
type mySessionImpl struct {}
func (me *mySessionImpl) Get(s string) Session {
return session.Get(s)
}
Run Code Online (Sandbox Code Playgroud)
现在,为了进行测试,我可以模拟SessionInterface并将其注入我的代码中