Skip to content

feat: Comparer interface for custom Equal assertions#1929

Open
sonnemusk wants to merge 1 commit into
stretchr:masterfrom
sonnemusk:feat/custom-comparer
Open

feat: Comparer interface for custom Equal assertions#1929
sonnemusk wants to merge 1 commit into
stretchr:masterfrom
sonnemusk:feat/custom-comparer

Conversation

@sonnemusk

Copy link
Copy Markdown

Summary

Adds assert.Comparer so domain types can define equality for Equal / NotEqual (and anything else using ObjectsAreEqual) without reflect.DeepEqual field-by-field noise (issue #1204).

type Money struct {
    Cents int
    Label string // display only
}

func (m Money) Equal(other interface{}) bool {
    o, ok := other.(Money)
    return ok && m.Cents == o.Cents
}

assert.Equal(t, Money{100, "$1.00"}, Money{100, "1 dollar"}) // true

Behavior

  • If expected implements Comparer, use expected.Equal(actual)
  • Else if actual implements Comparer, use actual.Equal(expected)
  • Else existing []byte / reflect.DeepEqual path

No codegen changes; only ObjectsAreEqual grows a short interface check.

Fixes #1204

Types may implement assert.Comparer so Equal/NotEqual use custom
equality instead of reflect.DeepEqual. Useful for money/decimal types
where different internal representations are equal in domain terms
(issue stretchr#1204).
Comment thread assert/assertions.go
return expected == actual
}

if c, ok := expected.(Comparer); ok {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This approach is not workable for the reasons I mentioned in #1204

This change would break existing tests which compare time.Time instances and expect to assert the time zone too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Custom assert equal comparator interface

2 participants