testify
testify copied to clipboard
Compare structs with unsorted slices
Hi! Are here any assert func to compare two struct contains same slices with the same elements but in differs order?
For example:
type Test struct {
Names []string
}
c1 := Test{
Names: []string{ "Joe", "Rick" }
}
c2 := Test{
Names: []string{ "Rick", "Joe" }
}
I need some func that can compare that two structs ignoring slice elems order in it.
It would also be amazing if we we could compare 2 json-strings this way - almost like JsonEq
, but using ElementsMatch
when comparing slices. We could name this new method JsonContentsMatch
or something along these lines.
Example usage:
expectedEvent := `{
"participants": ["Joe", "Rick"],
"event": "Birthday party"
}`
actualEvent := `{
"event": "Birthday party",
"participants": ["Rick", "Joe"]
}`
assert.JsonContentsMatch(t, expectedEvent, actualEvent)
Is it in the raodmap?
We can certainly add it. I'm going to spruce up the milestones this morning, I'll slot this in.
Hey @glesica just checking if this got added to the milestones? It would be an incredibly useful feature
I just ran into this with a slice nested down inside some structs. I'm using assert.EqualValues
on the structs and the assertion starts to fail when the slice order differs, which gets annoying in my case that conditionally adds values to the slice in question.
i have the same problem。assert.EqualValues
use reflect.DeepEqual
, it's hard to do what i want
This use case seems to be addressed by the assertions.ElementsMatch
method.
https://pkg.go.dev/github.com/stretchr/testify/assert?utm_source=godoc#ElementsMatch
@mchlp Yes and no...
It does solve it in the case the OP presented.
Now imagine you have struct
, with 20+ fields. And one of those fields is a slice
.
You cannot write:
assert.Equal(t, expectedResponse, receivedResponse)
But you have write:
assert.Equal(t, expectedResponse.field1, receivedResponse.field1)
assert.Equal(t, expectedResponse.field2, receivedResponse.field2)
...
assert.ElementsMatch(t, expectedResponse.field20, receivedResponse.field20)
And this is only the simple case without any nesting....
If I have to write this all out by hand, why am I even using an assertion library?
Potentially could be addressed by: https://github.com/stretchr/testify/issues/843#issuecomment-1952362012