douhao7889 2018-07-25 14:33
浏览 74

删除fmt.Println()时,golang中的猴子修补失败

While writing a test I have to patch a method in order to check that it is called, this is my code:

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
}

and this is the test:

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)
}

If I run the test like this, it will pass, but if I remove the fmt.Println() from SecondMethod, then the test fails (the test uses the original body of the method, not the patched one).

Also if I use debugging from Goland, the test passes even if SecondMethod has an empty body.

  • 写回答

1条回答 默认 最新

  • dparivln22034 2018-08-24 03:20
    关注

    This is caused by compiler's inline optimize, add -gcflags="-N -I" will disable it.

    评论

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭