Skip to content
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

How to mock protected properties? #1142

Open
kaysonwu opened this issue Sep 1, 2021 · 2 comments
Open

How to mock protected properties? #1142

kaysonwu opened this issue Sep 1, 2021 · 2 comments

Comments

@kaysonwu
Copy link

kaysonwu commented Sep 1, 2021

Does mockery support mock protected properties? What should I do if I can?

@LastDragon-ru
Copy link
Contributor

http://docs.mockery.io/en/latest/reference/protected_methods.html

LastDragon-ru added a commit to LastDragon-ru/lara-asp that referenced this issue Apr 28, 2024
LastDragon-ru added a commit to LastDragon-ru/lara-asp that referenced this issue Apr 28, 2024
LastDragon-ru added a commit to LastDragon-ru/lara-asp-testing that referenced this issue Apr 28, 2024
@LastDragon-ru
Copy link
Contributor

LastDragon-ru commented Apr 28, 2024

Alright, here is the correct answer - it is possible with a custom trait 😁 (Laravel 10+, PHP 8.1+; source) but with limitations:

  • Readonly properties should be uninitialized.
  • Private properties aren't supported.
  • Property value must be an object
    (only in this case we can track usage).
  • Property must be used while test.
  • Property can be mocked only once.
  • Objects without methods will be marked as unused
    (detection based on methods calls).
  • Performance is untested.
$mock = Mockery::mock(A::class, MockProperties::class);
$mock
    ->shouldUseProperty('b')
    ->value(
        Mockery::mock(B::class), // or just `new B()`.
    );

$mock->a();

Implementation is pretty simple but relies on internals :( Would be nice if Mockery will support something similar out of the box (readonly and upcoming hooks make getters useless imo). The main difficulty - check if any of methods were called, to mark that property was used. Seems there is no built expectation for this case, and I've no idea how to implement it properly.

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

No branches or pull requests

2 participants