unit-testing - 当我删除 fmt.Println() 时,golang 中的猴子修补失败

标签 unit-testing go monkeypatching

在编写测试时,我必须修补一个方法以检查它是否被调用,这是我的代码:

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/

相关文章:

unit-testing - 对需要Electron的Angular2服务进行单元测试

go - 如何将 zap 记录器与 go-kit 一起使用?

javascript - MonkeyPatching:PrimeFaces 小部件扩展/覆盖

Python 套接字实现

python - 猴子补丁方法和引用的问题

c# - 我如何使用 Moq 或 NInject 模拟内核模拟接口(interface)

java - maven 无法从测试用例中找到任何包

java - URLConnection 上的 JUnit 测试,使用 EasyMock?

go - 尝试了解如何从 int params 构建数组

go - 如何在字符串文字中转义反引号