testify icon indicating copy to clipboard operation
testify copied to clipboard

Ignore fields using struct tags

Open hiimoliverwang opened this issue 5 years ago • 3 comments

Hello,

Is there a way to ignore certain fields when asserting equal or as the argument of .On?

e.g.

type A struct {
  Name string
  UpdatedAt time.Time `mock: "ignore"`
}

expected := A{
    Name: "Expected Name"
}
mocks.MockController.On("Update", expected).Return(whatever)
...

We don't really care about the UpdateAt time, and this would also apply to random UUID's etc. Otherwise we would have to assert each sub field in order for the test to pass.

hiimoliverwang avatar Nov 12 '19 17:11 hiimoliverwang

Not that I am aware of, would it make sense in your use case to explicitly assert the fields (if the include list is small) or conversely shallow-copy the struct and remove the ones you don't want to compare (if the exclude list is small)?

boyan-soubachov avatar Dec 04 '19 07:12 boyan-soubachov

Hello. Is there any news on this? I have the issue described, and I cannot use the suggested ways of @boyan-soubachov because it's intricated controllers so I don't get to manipulate the intermediate result used by the mock.

Khyme avatar Sep 27 '21 14:09 Khyme

I think this could be a good approach for the issues people face with comparing nested time.Time objects and unsorted array types? Struct tags could override the comparison used, for example:

my_code.go

...

type MyAmazingThing struct {
    ID string
    Created time.Time
    Documents []string
    DeleteFn func() error
}

...

my_code_test.go

...

type myAmazingThingEqual struct {
    ID string
    Created time.Time     // `testify:"WithinDuration,0"`
    Documents []string    // `testify:"ElementsMatch"`
    DeleteFn func() error // `testify:"ignore"`
}

assert.Equal(t, expected, myAmazingThingEqual(actual))

...

brackendawson avatar Feb 19 '24 12:02 brackendawson