Last active
December 19, 2023 11:08
-
-
Save jakzal/5555451 to your computer and use it in GitHub Desktop.
Mocking ArrayAccess with prophecy in phpspec
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class MyThing | |
{ | |
private $myArray = null; | |
public function __construct($myArray) | |
{ | |
$this->myArray = $myArray; | |
} | |
public function getFromArray($name) | |
{ | |
return $this->myArray[$name]; | |
} | |
public function __call($method, $arguments) | |
{ | |
$field = lcfirst(substr($method, 3)); | |
return $this->getFromArray($field); | |
} | |
public function __get($name) | |
{ | |
return $this->getFromArray($name); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace spec; | |
use PhpSpec\ObjectBehavior; | |
class MyThingSpec extends ObjectBehavior | |
{ | |
function let(\ArrayAccess $myArray) | |
{ | |
$this->beConstructedWith($myArray); | |
} | |
function it_retrieves_my_array_details(\ArrayAccess $myArray) | |
{ | |
$myArray->offsetGet('foo')->shouldBeCalled()->willReturn('bar'); | |
$this->getFromArray('foo')->shouldReturn('bar'); | |
} | |
function it_retrieves_my_array_details_with_a_magic_call(\ArrayAccess $myArray) | |
{ | |
$myArray->offsetGet('foo')->shouldBeCalled()->willReturn('bar'); | |
$this->getFoo()->shouldReturn('bar'); | |
} | |
function it_retrieves_my_array_details_by_accessing_a_property(\ArrayAccess $myArray) | |
{ | |
$myArray->offsetGet('foo')->shouldBeCalled()->willReturn('bar'); | |
$this->foo->shouldReturn('bar'); | |
} | |
} |
@martcor in retrospect, I would not mock ArrayAccess nor any native language behaviour. Just create the thing.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Awesome! I think this should be added to the official documentation somewhere!
The
\ArrayAccess
can't be used in all situations as described in official documentation.