Mock Method Calls
Here are some examples of mocking method calls with Enhance PHP. If you aren't interested in using the mock to verify the expectations as part of a test, you might be more interested in
using a stub
- the syntax for both is very similar, but the stub is not used to pass or fail a test.
Getting A Mock Class
$mock = \Enhance\MockFactory::createMock('MyClassName');
To get a mock class, simply ask the MockFactory to create a mock and pass in the name of the class.
Typical Usage
Typically, you will want to set all of the different parameters for a mocked method.
$mock->addExpectation(\Enhance\Expect::method('getSomething')->with(1, 'Arg2')->returns('Something')->times(1));
In this example we set the following:
-
method('getSomething')
The method (or function) being called is the getSomething() method.
-
with(1, 'Arg2')
The getSomething method is being called with two arguments, an integer and a string, i.e. getSomething(1, 'Arg2') -
returns('Something')
or
throws('Error Message')
The getSomething method will return a string 'Something' -
times(1)
The getSomething method should be called 1 time exactly
If you want the expectation to be verified as part of your test (which is the purpose of a mock), you must call the verifyExpectations method at the end of your test:
$mock->verifyExpectations();
Mock An Exception
$mock->addExpectation(\Enhance\Expect::method('getSomething')->with(1, 'Arg2')->throws('Exception message.')->times(1));