unit-testing - 当我删除 fmt.Println() 时,golang 中的猴子修补失败
问题描述
在编写测试时,我必须修补一个方法以检查它是否被调用,这是我的代码:
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)
}
如果我像这样运行测试,它将通过,但如果我fmt.Println()
从 SecondMethod 中删除,则测试失败(测试使用方法的原始主体,而不是修补的主体)。
此外,如果我使用 Goland 的调试,即使 SecondMethod 的主体为空,测试也会通过。
解决方案
这是由编译器的内联优化引起的,添加-gcflags="-N -I"
将禁用它。
推荐阅读
- python - Python从单独文件夹中的jupyter笔记本访问excel文件
- fpga - 使用 PC 对 FPGA 施加激励
- java - Java Callable 和 Future 没有异步运行
- arm - Cortex-X1 上的内存延迟
- java - 通话后(应用程序关闭时)应该会出现一个浮动小部件
- sql - 如何使用 json 函数遍历 bigQuery 中的 json 对象
- logging - GCP | Stackdriver 日志记录 | 过滤器 | 必需的字符串
- jenkins - 我应该如何保存 Jenkins 管道结果?
- apache-spark - 将 sql-spark-connector 库安装到 Azure Synapse Apache Spark
- c# - 如何获取 csv 字符串格式的子表项的计数