Skip to content

Adds AnythingOfTypeT wrapper function - #1336

Open
chrsalx wants to merge 6 commits into
stretchr:masterfrom
chrsalx:master
Open

chrsalx wants to merge 6 commits into
stretchr:masterfrom
chrsalx:master

Conversation

@chrsalx

@chrsalx chrsalx commented Feb 1, 2023 •

Copy link
Copy Markdown

Summary

Adds AnythingOfTypeT function as a wrapper that provides generics support to AnythingOfType.

Changes

  • bumps go.mod version to 1.19.
  • Adds AnythingOfTypeT function.
  • Adds tests for AnythingOfTypeT.

Motivation

The AnythingOfType function allows us to configure mocking behavior for any value for the provided type. The caveat to this is that AnythingOfType expects a string, this requires the user to know beforehand the full name of the type as it will be defined by Go at runtime.

This can lead to issues during the development of the tests caused by typos or by not naming the desired type properly.

Using generics, Go can provide the name of the type without breaking the existing API.

c := mockedService.
	On("TestMethod", AnythingOfTypeT[int]()).
	Return(nil)

assert.Nil(t, c.TestMethod(5))

@dolmen dolmen added the pkg-mock Any issues related to Mock label Jul 6, 2023
@dolmen

dolmen commented Jul 6, 2023

Copy link
Copy Markdown
Collaborator

The testify module doesn't yet rely on a Go version that has generics. testify is now a major point in the Go ecosystem, so it would not be wise yet to block users from upgrading testify (to benefit from bug fixes) if they are not able to upgrade their Go toolchain (example: support of a GOOS or GOARCH being removed in recent versions).

So that new code that use generics must be put in a separate file mock_generics.go with a //go:build go1.18 guard.

@dolmen dolmen added this to the v2.0.0 milestone Jul 6, 2023
@dolmen

dolmen commented May 12, 2026

Copy link
Copy Markdown
Collaborator

We have mock.IsType: this is the function that should have a generic version. So prefix should be IsType, not AnythingOfType.

@dolmen dolmen added the mock.ArgumentMatcher About matching arguments in mock label May 12, 2026
@dolmen

dolmen commented May 12, 2026

Copy link
Copy Markdown
Collaborator

See also #1442.

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

Labels

enhancement mock.ArgumentMatcher About matching arguments in mock pkg-mock Any issues related to Mock

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants