Skip to content

Instantly share code, notes, and snippets.

@jamiehannaford
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamiehannaford/ad7f389466ac5dcafe7a to your computer and use it in GitHub Desktop.
Save jamiehannaford/ad7f389466ac5dcafe7a to your computer and use it in GitHub Desktop.
<?php
class AddressBook
{
private $users = [];
public function addUser(UserInterface $user)
{
$user->registerAsAdded();
if ($user->isLocal()) {
$this->users[] = $user;
}
}
public function getCount()
{
return count($this->users);
}
}
class AddressBookTest extends TestCase
{
private $addressBook;
public function setUp()
{
$this->addressBook = new AddressBook();
}
public function testNonLocalUserIsNotAdded()
{
$userMock = $this->getMock('UserInterface');
// Tell the mock to return FALSE for the "isLocal" method
$userMock->expects($this->once())->method('isLocal')->will($this->returnValue(false));
$this->addressBook->addUser($userMock);
$this->assertEquals(0, $this->addressBook->getCount());
}
public function testLocalUserIsAdded()
{
$userMock = $this->getMock('UserInterface');
// Tell the mock to return TRUE for the "isLocal" method
$userMock->expects($this->once())->method('isLocal')->will($this->returnValue(true));
$this->addressBook->addUser($userMock);
$this->assertEquals(1, $this->addressBook->getCount());
}
public function testUserGetsRegistered()
{
$userMock = $this->getMock('UserInterface');
// Tell the mock that "registerAsAdded" will be called exactly once. When you
// use the "expects" method on a mock, you're actually setting up an explicit
// test expectation. Here we say "$this->once()" - but we could also pass in
// "$this->exactly(1)". If it's called *less* or *more* than once, this test will fail.
$userMock->expects($this->once())->method('registerAsAdded');
// Because we've set up expectations on our mock, we don't need assertions here
$this->addressBook->addUser($userMock);
}
}
@jamiehannaford
Copy link
Author

Instead of instantiating the $userMock variable in our tests, we could have also done it in our setUp method and saved it to a class property.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment