这个问题:如何测试Go中的os.exit场景(以及其中最高的投票答案),阐述了如何os.Exit()在go中测试场景.由于os.Exit()不能轻易拦截,使用的方法是重新调用二进制文件并检查退出值.这个方法在Andrew Gerrand(Go团队的核心成员之一)的演示文稿第23页中描述; 代码非常简单,下面将全文转载.
相关的测试和主文件看起来像这样(请注意,这对文件本身就是一个MVCE):
package foo
import (
"os"
"os/exec"
"testing"
)
func TestCrasher(t *testing.T) {
if os.Getenv("BE_CRASHER") == "1" {
Crasher() // This causes os.Exit(1) to be called
return
}
cmd := exec.Command(os.Args[0], "-test.run=TestCrasher")
cmd.Env = append(os.Environ(), "BE_CRASHER=1")
err := cmd.Run()
if e, ok := err.(*exec.ExitError); ok && !e.Success() {
fmt.Printf("Error is %v\n", e)
return
}
t.Fatalf("process ran with err %v, want exit status 1", err)
}
Run Code Online (Sandbox Code Playgroud)
和
package …Run Code Online (Sandbox Code Playgroud) 首先,我要说我是Go语言的新手,因此在与其他库一起使用时,我正在寻找模拟技术。我很清楚接口和依赖注入是使代码可测试和可模拟的最佳方法。
在使用第三方客户端库(Google云存储)时,尝试模拟其客户端的实现时遇到了问题。主要问题是客户端库中的类型未使用接口实现。我可以生成模仿客户端实现的接口。但是,某些函数的返回值将返回指向基础结构类型的指针,由于私有属性,这些指针很难或无法模拟。这是我要解决的问题的样本:
package third_party
type UnderlyingType struct {
secret string
}
type ThirdPartyClient struct {}
func (f *ThirdPartyClient) SomeFunction() *UnderlyingType {
return &UnderlyingType{
secret: "I can't mock this, it's a secret to the package"
}
}
Run Code Online (Sandbox Code Playgroud)
这是带注释的示例,其中包含我要解决的问题。
package mock
// Create interface that matches third party client structure
type MyClientInterface interface {
SomeFunction() *third_party.UnderlyingType
}
type MockClient struct {
third_party.Client
}
// Forced to return the third party non-interface type 'UnderlyingType'
func (f *MockClient) SomeFunction() *UnderlyingType {
// No way …Run Code Online (Sandbox Code Playgroud)