The Mockery is creating the dummy/mock object. It is very very powerful mock Library. We use to test at my PHP Application. But so difficult of how to use becouse Mockery is powerful in my brain.
- Link: mockery/mockery
- Link: hamcrest/hamcrest-php
by the way, I'll update this sometime.
Check the call method AT ONLY ONCE
$mock = Mockery::mock(App\Custom\Class::class);
$mock->shouldReceive('method')->once()->andReturn(1);
or
$mock = Mockery::mock(App\Custom\Class::class);
$mock->expects()->method()->once()->andReturn(1);
Check the call method AT 5 time
$mock = \Mockery::mock( App\Custom\Class::class );
$mock->shouldReceive('method_222')
->times( 5 );
Check the no call method / never call
$mock = Mockery::mock(App\Custom\Class::class);
$mock->shouldNotReceive('method');
// or
$mock->shouldReceive('method')->never();
I do not know what different to shouldNotReceive
and never
.
Argument Pattern
Sometime, I want to check the arguments value and instance type.
( I do not like a helper function. I thought these are simple, and I lost where from. I don't write equalTo
, I write \Hamcrest\Matchers::equalTo
at all. )
$mock = Mockery::mock(App\Custom\Class::class);
// String check
$mock->shouldReceive('toInt')
->with(\Mockery::pattern('/\A[0-9]+\z/'))
->andReturns(1);
// or
$mock->shouldReceive('toInt')
->with(\Hamcrest\Matchers::matchesPattern('/\A[0-9]+\z/'))
->andReturns(1);
// Object Exact Comparion Check
$object = new stdClass();
$mock->shouldReceive('method_2')
->with($object);
// or
$mock->shouldReceive('method_2')
->with(\Hamcrest\Matchers::equalTo($object));
// Object Class check
$mock->shouldReceive('method_3')
->with(\Hamcrest\Matchers::equalTo(new stdClass));
// resource type
$mock->shouldReceive('method_4')
->with(\Hamcrest\Matchers::resourceValue());
Argument Numeric Check
$mock = Mockery::mock(App\Custom\Class::class);
// 2 <= $arg < 4
$mock->shouldReceive('method_10')
->with(\Hamcrest\Matchers::closeTo(2, 4));
// $arg === 2
$mock->shouldReceive('method_11')
->with(\Hamcrest\Matchers::comparesEqualTo(2));
Arugment must be not match
$mock = Mockery::mock(App\Custom\Class::class);
// error argument value is 1 or 2
$mock->shouldReceive('method_20')
->with(\Mockery::notAnyOf(1, 2));
Only check the argument.
I check to call the method with the argument, but not check these instance/class. Only with the argument.
$mock = Mockery::mock(App\Custom\Class::class);
$mock->shouldReceive('method_4')
->with(\Mockery::any());
// or
$mock->shouldReceive('method_4')
->with(\Hamcrest\Matchers::anything());
Spy
Sometime, I want to check after the calling method in object. Spy can checked after calling the method.
But, Spy is weaker than mock. Spy's method can not return the value. This ability has only mock.
// arrange
$spy = \Mockery::spy('MyDependency');
$sut = new MyClass($spy);
// act
$sut->callFoo();
// assert
$spy->shouldHaveReceived()
->foo()
->with('bar');
Top comments (0)