Phake - PHP Mocking Framework

Prev   Next

Stubbing Magic Methods

The verification of __call() was discussed in the previous chapter. Magic methods can also be stubbed in much the same way. If you want to verify a particular invocation of __call() you can stub the actual method call by mocking the method passed in as the first parameter.

Consider the following class.

Example 2.17. A Magic Class

<?php
class MagicClass
{
public function __call($method, $args)
{
return '__call';
}
}
?>

You could stub an invocation of the __call() method through a userspace call to magicCall() with the following code.

Example 2.18. Implicitly Stub of __call()

<?php
class MagicClassTest extends PHPUnit_Framework_TestCase
{
  public function testMagicCall()
  {
    $mock = Phake::mock('MagicClass');

    Phake::when($mock)->magicCall()->thenReturn(42);

		$this->assertEquals(42, $mock->magicCall());
  }
}
?>

If for any reason you need to explicitly stub calls to __call() then you can use Phake::whenCallMethodWith().

Example 2.19. Explicitly Stubbing __call()

<?php
class MagicClassTest extends PHPUnit_Framework_TestCase
{
  public function testMagicCall()
  {
    $mock = Phake::mock('MagicClass');

    Phake::whenCallMethodWith('magicCall')->isCalledOn($mock)->thenReturn(42);

		$this->assertEquals(42, $mock->magicCall());
  }
}
?>

Prev   Next
Introduction to Phake
1. Getting Started
Support
2. Method Stubbing
Basic Method Stubbing
How Phake::when() Works
Overwriting Existing Stubs
Stubbing Multiple Calls
Stubbing Consecutive Calls
Stubbing Reference Parameters
Partial Mocks
Setting Default Stubs
Stubbing Magic Methods
3. Method Verification
Basic Method Verification
Verifying Method Parameters
Verifying Multiple Invocations
Verifying Calls Happen in a Particular Order
Verifying No Interaction with a Mock so Far
Verifying No Further Interaction with a Mock
Verifying Magic Methods
4. Answers
Throwing Exceptions
Calling the Parent
Capturing a Return Value
Custom Answers
5. Method Parameter Matchers
Using PHPUnit Matchers
Using Hamcrest Matchers
Parameter Capturing
Custom Parameter Matchers
6. Configuration
Setting the Phake Client
Setting the Mock Class Loader

Copyright © 2011 Mike Lively

This page uses the Perfect 'Left Menu' 2 Column Liquid Layout by Matthew James Taylor.