stretchr / testify

A toolkit with common assertions and mocks that plays nicely with the standard library
MIT License
22.92k stars 1.58k forks source link

Ignore fields using struct tags #843

Open hiimoliverwang opened 4 years ago

hiimoliverwang commented 4 years ago

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.

boyan-soubachov commented 4 years ago

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)?

Khyme commented 2 years ago

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.

brackendawson commented 6 months ago

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))

...