mockery / mockery

Mockery is a simple yet flexible PHP mock object framework for use in unit testing with PHPUnit, PHPSpec or any other testing framework. Its core goal is to offer a test double framework with a succinct API capable of clearly defining all possible object operations and interactions using a human readable Domain Specific Language (DSL).
http://docs.mockery.io/en/stable/
BSD 3-Clause "New" or "Revised" License
10.61k stars 460 forks source link

How to mock protected properties? #1142

Open kaysonwu opened 3 years ago

kaysonwu commented 3 years ago

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

LastDragon-ru commented 3 years ago

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

LastDragon-ru commented 4 months ago

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

$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.