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.