Repository navigation
Correct way to assert.Equal structs that contain functions pointers #1686
|
Hello, I'm having troubles comparing objects indirectly referencing function pointers. For the reference, here's a minimal example: package main
import (
"testing"
assert "github.com/stretchr/testify/assert"
)
type s struct {
f func()
}
func TestAssert(t *testing.T) {
var f = func() {}
var obj = s{f}
assert.Equal(t, obj, obj)
}Testing this code leads to this error: In my specific case, this function pointer field comes from a private nested structure I don't have the ability to manipulate. Is there a way to compare structures indirectly embedding a function pointer? |
Replies: 8 comments 1 reply
|
As is mentioned in equal's docs functions are only equal if they are both nil. Looking in the source of the reflect package, any further comparison is apparently not possible in Go. Unfortunately it looks like you'll need to compare each non-function field individually. If you need to check the function fields then you'll probably need to test code which calls them for state. |
From what I got, it is not possible to just ignore function pointers, then? I saw By the way, #535 mentions switching from
It's quite complicated in this very specific case, where the function pointer appears in a 3-levels nested private struct. |
|
It will definitely be worth considering this case when switching to go-cmp, so thanks for linking the issues, hopefully that's picked up. It would almost certainly be something for a testify v2 release, which has been proposed but I'm not sure it's coming any time soon as the maintainers of this project seem quite stretched. I'm fairly certain there isn't a way to do this using only testify. 😔 |
|
I've been having the same problem. |
|
bump |
In case anyone has the same problem, I ended up testing the type and then comparing the fields manually |
require.Equal(fmt.Sprint(tt.wantFunc), fmt.Sprint(actFunc))solved my problem //go:build testmode
package mypackagetype
// need flag
// -tags testmode
type stringFunc struct {
i int
f string
}
func NewStringFunc(orig origFunc) stringFunc {
return stringFunc{i: orig.i, f: fmt.Sprint(orig.f)}
}require.Equal(NewStringFunc(tt.want), NewStringFunc(act)) |
|
Format to string works for me: |
Format to string works for me: