-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add closure mocks #5759
base: main
Are you sure you want to change the base?
Add closure mocks #5759
Conversation
512dd4b
to
acdef4d
Compare
Codecov ReportAttention: Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #5759 +/- ##
============================================
- Coverage 90.08% 90.08% -0.01%
- Complexity 6588 6592 +4
============================================
Files 694 695 +1
Lines 19952 19961 +9
============================================
+ Hits 17974 17981 +7
- Misses 1978 1980 +2 ☔ View full report in Codecov by Sentry. |
Mocking closures is doable today by mocking __invoke on an invokable class. However this is troublesome, as it requires writing an invokable class, and mocking a class method. This new helper makes things easier via a new `$this->createClosureMock()` method.
/** | ||
* @mixin \PHPUnit\Framework\MockObject\MockObject | ||
* | ||
* @method InvocationMocker method($constraint) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't understand why Psalm does not recognize this annotation. PhpStorm does, and I used the same annotation as in MockObject
:
* @method InvocationMocker method($constraint) |
The problem
Mocking closures is doable today by mocking
__invoke
on an invokable class. However, this is troublesome, as it requires writing an invokable class and mocking a class method (which is confusing, hard to figure out, and makes tests harder to understand afterward).Here is another approach that is verbose and fragile:
The solution
This new helper makes things easier via a new
$this->createClosureMock()
method.Here's the test above rewritten using the new helper:
This is essentially just a shortcut to the workaround that is doable today, so this PR should not introduce too much new code.
Related to #3536
Note that #3536 mentioned a workaround using
stdClass
. I was not able to make it work: PHPUnit refused to mock stdClass's__invoke
method because it does not exist.This is, to me, yet another reason to have such a helper.