Skip to content

mock: add OnF method#1814

Open
burik666 wants to merge 3 commits into
stretchr:masterfrom
burik666:OnF
Open

mock: add OnF method#1814
burik666 wants to merge 3 commits into
stretchr:masterfrom
burik666:OnF

Conversation

@burik666
Copy link
Copy Markdown

@burik666 burik666 commented Oct 18, 2025

Summary

Adds method OnF to mock.Mock and mock.Call to allow defining mock expectations using function references instead of string method names.

Changes

  • Added OnF method to mock.Mock and mock.Call.
  • OnF extracts the function name using reflection and runtime information (runtime.FuncForPC).
  • Provides a more type-safe, refactor-friendly alternative to On.

Motivation

Currently, mock expectations are defined using string literals for method names, which can be error-prone and break easily during refactoring.
OnF allows developers to use actual function references, improving type safety and maintainability.

Related issues

@burik666
Copy link
Copy Markdown
Author

bump.
what do you think about this?

@dolmen dolmen added pkg-mock Any issues related to Mock enhancement: extend API An enhancement that grows the API surface labels Feb 17, 2026
@dolmen
Copy link
Copy Markdown
Collaborator

dolmen commented May 12, 2026

I like the implementation, but I don't like the method name.

Comment thread mock/mock.go
// Mock.
// On("MyMethod", 1).Return(nil).
// On("MyOtherMethod", 'a', 'b', 'c').Return(errors.New("Some Error"))
//
Copy link
Copy Markdown
Collaborator

@dolmen dolmen May 12, 2026

Choose a reason for hiding this comment

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

Add link to OnF with a godoc link to make the new method more discoverable (especially by agents).

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Added a short godoc cross-reference to OnF from On to improve discoverability.

@burik666
Copy link
Copy Markdown
Author

@dolmen

I don't like the method name.

Renamed to OnFn.
Feels consistent with the existing On method while being a bit clearer.

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

Labels

enhancement: extend API An enhancement that grows the API surface pkg-mock Any issues related to Mock

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Use function pointers to set up mock expectations

2 participants