首页 > 解决方案 > 当我删除 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 的主体为空,测试也会通过。

标签: unit-testinggomonkeypatching

解决方案


这是由编译器的内联优化引起的,添加-gcflags="-N -I"将禁用它。


推荐阅读