How to use gomega's ContainElements matcher with a custom equality matcher

1.7k Views Asked by At

In a test I have a list actual of elements with a struct similar to this:

type MyStruct struct {
     Field1 string
     Field2 int32
     .
     .       // a long list of other fields
     .

}

I want to assert that actual contains the elements of a list of expected elements, but only considering Field1 and Field2, the other fields are not relevant for the test. I would like to use the ContainElements matcher with some "magic" custom matcher like in this pseudo code:

expected := []MyStruct{{Field1: "value1", Field2: 1} ...{Field1: "value2", Field2: 2}}
Expect(actual).To(ContainElements(expected), <custom matcher>)

I have been looking at the WithTransform matcher as in [1] but I have been unable to figure out how to use it in this context.

[1] http://eng.rightscale.com/2015/11/30/composing-gomega-matchers.html

2

There are 2 best solutions below

0
On

You can use MatchFields(IgnoreExtras, Fields{}) to compare only given fields so in your case it should look something like:

ContainElement(MatchFields(IgnoreExtras,Fields{
                    "Field1": Equal("Value1"),
                    "Field2": Equal(int32(42)),
                }))
0
On

I think you can use the customized gomega matcher respect directly. It looks like

expected := []MyStruct{{Field1: "value1", Field2: 1} ...{Field1: "value2", Field2: 2}}
Expect(actual).To(Respcet(expected))