We are testing a simple controller from imaginable MVC framework.
<?php
class UserController extends AbtractController {
public function show($id)
{
$user = $this->db->find('users',$id);
if (!$user) return $this->render404('User not found');
$this->render('show.html.php', array('user' => $user));
return true;
}
}
It's a new testing framework. It's here, on GitHub: https://github.com/Codeception/Codeception
<?php
class UserControllerCest {
public $class = 'UserController';
public function show(CodeGuy $I) {
// prepare environment
$I->haveFakeClass($controller = Stub::make($this->class, array('render' => function() {}, 'render404' => function() {})))
->haveFakeClass($db = Stub::make('DbConnector', array('find' => function($id) { return $id > 0 ? new User() : null )))
->setProperty($controller, 'db', $db);
$I->executeTestedMethodOn($controller, 1)
->seeResultEquals(true)
->seeMethodInvoked($controller, 'render');
$I->expect('it will render404 for unexistent user')
->executeTestedMethodOn($controller, 0)
->seeResultNotEquals(true)
->seeMethodInvoked($controller, 'render404','User not found')
->seeMethodNotInvoked($controller, 'render');
}
}
<?php
class UserControllerTest extends PHPUnit_Framework_TestCase
{
protected function prepareController()
{
$controller = $this->getMock('UserController', array('render', 'render404'), null, false, false);
$db = $this->getMock('DbConnector');
$db->expects($this->any())
->method('find')
->will($this->returnCallback(function ($id)
{
return $id > 0 ? new User() : null;
}));
// connecting stubs together
$r = new ReflectionObject($controller);
$dbProperty = $r->getProperty('db');
$dbProperty->setAccessible(true);
$dbProperty->setValue($controller, $db);
}
public function testShowForExistingUser()
{
$controller = $this->prepareController();
$controller->expects($this->once())->method('render')->with($this->anything());
$this->assertTrue($controller->show(1));
}
public function testShowForUnexistingUser()
{
$controller = $this->prepareController();
$controller->expects($this->never())->method('render')->with($this->anything());
$controller->expects($this->once())
->method('404')
->with($this->equalTo('User not found'));
$this->assertNotEquals(true, $controller->show(0));
}
}