-
-
Save jamiehannaford/ad7f389466ac5dcafe7a to your computer and use it in GitHub Desktop.
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 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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Instead of instantiating the
$userMock
variable in our tests, we could have also done it in oursetUp
method and saved it to a class property.