Mocks And Stubs
Enhance PHP has built-in support for mocks and stubs. You can set up expectations and supply predictable return values.
You can simply create a mock and then add an expectation and then check that the expectation has been met. Here is an example:
class ExampleDependencyClassTests extends \Enhance\TestFixture { public function verifyWithAMock() { $mock = \Enhance\MockFactory::createMock('ExampleDependencyClass'); $mock->addExpectation( \Enhance\Expect::method('getSomething') ->with(1, 'Arg2') ->returns('Something') ->times(1) ); $target = new ExampleClass($mock); $result = $target->doSomething(); $mock->verifyExpectations(); } }
The call to \Enhance\MockFactory::createMock just requires the name of the class you want to mock.
The call to $mock->addExpectation takes in an expectation with the following aspects:
The first call should be to one of the following:
-
method('MethodName')
The name of the method to be mocked -
getProperty('PropertyName')
The name of a property to be mocked, which will be called
-
setProperty('PropertyName')
The name of a property to be mocked, which will be set
Subsequent calls can be made to any combination of the following:
-
with(arg, arg, arg...)
Optional - you can specify the exact arguments to be matched on the call. If you don't mind what the arguments are, don't specify the with(). -
returns(returnValue)
Optional - you can specify the return value to be returned when the matching call is made. You can omit this to return nothing. -
throws(exceptionMessage)
Optional - you can specify an exception to be thrown when the matching cal is made. Only use this if you want the mock to throw an exception rather than return a value.
-
times(number)
Optional - you can specify the number of times the call should be made.
The return value supplied will only be returned when the matching call is made. The mock will not error unless you call $mock->verifyExpectations();
If you want to make a stub rather than a mock, call \Enhance\StubFactory::createStub(). You cannot call "verifyExpectations" on a Stub.
Important note - Unexpected Calls
With a mock, if a call is made to a method or property for which there is no expectation, an error will be thrown. If you want a method to be stubbed (i.e. not to be tracked so no errors are thrown) simply set a general expectation:
$mock->addExpectation(\Enhance\Expect::method('getSomething'));
With a stub, you can make unexpected calls without errors.