在编写测试时,我必须修补一个方法以检查它是否被调用,这是我的代码:
import "fmt"
type myStruct struct {}
func (myObject *myStruct) firstMethod() {
myObject.SecondMethod()
}
func (myObject *myStruct) SecondMethod() {
fmt.Println("Inside the original SecondMethod") //test fails if I remove this
}
这是测试:
import (
"reflect"
"testing"
"github.com/bouk/monkey"
"github.com/stretchr/testify/assert"
"fmt"
)
func TestThatSecondMethodIsCalled(t *testing.T) {
myObject := &myStruct{}
wasCalled := false
monkey.PatchInstanceMethod(
reflect.TypeOf(myObject),
"SecondMethod",
func(*myStruct) {
fmt.Println("Inside the replacement of SecondMethod")
wasCalled = true
},
)
myObject.firstMethod()
assert.True(t, wasCalled)
}
如果我这样运行测试,它会通过,但是如果我从 SecondMethod 中删除 fmt.Println()
,那么测试就会失败(测试使用方法的原始主体,不是打补丁的)。
此外,如果我使用 Goland 调试,即使 SecondMethod 的主体为空,测试也会通过。
最佳答案
这是由编译器的内联优化引起的,添加-gcflags="-N -I"
将禁用它。
关于unit-testing - 当我删除 fmt.Println() 时,golang 中的猴子修补失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51521539/