Last active
August 29, 2015 14:13
-
-
Save partageit/655774bd8892a9c0d908 to your computer and use it in GitHub Desktop.
Partage-it.com : création d'une classe pour son utilisation en tant que mock avec Atoum en PHP
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 | |
// src/UsersManager.php | |
namespace Vendor\Users; | |
class UsersManager { | |
private $users = array(); | |
/** | |
* Add a user to the list | |
* @return User|boolean Return the created user object, or false if the user is not valid | |
*/ | |
public function addUser($firstName, $lastName) { | |
$user = new User($firstName, $lastName); | |
if ($user->isValid()) { | |
$this->users[] = $user; | |
return $user; | |
} else { | |
return false; | |
} | |
} | |
} | |
class User { | |
private $firstName; | |
private $lastName; | |
private $webService; | |
public function __construct($firstName, $lastName) { | |
$this->firstName = $firstName; | |
$this->lastName = $lastName; | |
$this->webService = new \Web\Service\WebService(); | |
} | |
public function isValid() { | |
// perform connection to an external service and return the result (true or false) | |
return $webService->isValid($this->firstName . " " . $this->lastName); | |
} | |
public function unregister() { | |
return $webService->unregister(); | |
} | |
} | |
?> |
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 | |
// tests/UsersManager.php | |
namespace Vendor\Users\tests\units; | |
use atoum; | |
class fakeUser { | |
private $firstName; | |
private $lastName; | |
public function __construct($firstName, $lastName) { | |
$this->firstName = $firstName; | |
$this->lastName = $lastName; | |
} | |
/** | |
* Return false when the first name begins with 'not-valid' | |
*/ | |
public function isValid() { | |
return (strpos($this->firstName, "not-valid") === 0); | |
} | |
} | |
class UsersManager extends atoum { | |
public function beforeTestMethod() { | |
$this->mockGenerator->generate('\Vendor\Users\tests\units\fakeUser', '\Vendor\Users', 'User'); | |
} | |
public function testValidUser() { | |
$this | |
->given($m = new \Vendor\Users\UsersManager()) | |
->object($m->addUser("Maurice", "Moss")) | |
// The class name is the real one, not the fake one, even it is a mock class: | |
->isInstanceOf('\Vendor\Users\User'); | |
} | |
public function testInvalidUser() { | |
$this | |
->given($m = new \Vendor\Users\UsersManager()) | |
->boolean($m->addUser("not-valid-Maurice", "Moss")) | |
->isEqualTo(false); | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment