Skip to content

Instantly share code, notes, and snippets.

@ahmed-abid
Created January 28, 2018 14:07
Show Gist options
  • Save ahmed-abid/1b1289e958ea5a148636d8c84d59dffa to your computer and use it in GitHub Desktop.
Save ahmed-abid/1b1289e958ea5a148636d8c84d59dffa to your computer and use it in GitHub Desktop.
PHP code is now 99% testable with AspectMock
<?php
namespace tests\AspectMock;
use Codeception\TestCase\Test;
use App\AspectMock\UserModel;
use App\AspectMock\NoDependencyInjectionNeeded;
use App\AspectMock\User2;
use AspectMock\Test as Moke;
class AspectMockTest extends Test
{
/** simple mock example */
public function testTableName()
{
$tableName = UserModel::tableName();
$this->assertEquals('users', $tableName);
$userModel = Moke::double('App\AspectMock\UserModel', ['tableName' => 'my_users']);
$name = UserModel::tableName();
$this->assertEquals('my_users', $name);
$userModel->verifyInvoked('tableName');
}
/** no dependency injection example */
public function testNoDependencyInjectionNeeded(){
$object = new NoDependencyInjectionNeeded();
$original = $object->getName();
$this->assertEquals('users — No Dependency Injection Needed', $original);
Moke::double('App\AspectMock\UserModel', ['tableName' => 'my_users']);
$mokedName = $object->getName();
$this->assertEquals('my_users — No Dependency Injection Needed', $mokedName);
}
public function testTime()
{
$timeProxy = Moke::func('tests\AspectMock', 'time', 'now');
$now = time();
$now1 = time();
$this->assertEquals($now, $now1);
$timeProxy->verifyInvokedMultipleTimes(2);
$timeProxy = Moke::func('App\AspectMock', 'time', 'year');
$user2 = new User2('abid');
$now = $user2->getTime();
$now1 = $user2->getTime();
$this->assertEquals($now, $now1);
$timeProxy->verifyInvokedMultipleTimes(2);
}
public function testAnyThing()
{
$user = Moke::spec('Undefined')->construct();
$user->can()->be->called()->anything();
$user->can['be used as array'];
foreach ($user->names as $name) {
$name->canBeIterated();
}
}
public function testCallsForASpecificMethod()
{
$user = Moke::double('App\AspectMock\UserModel');
$return = UserModel::someMethod('1111', '2222');
$this->assertEquals('1111 2222', $return);
$callsForMethod = $user->getCallsForMethod('someMethod'); // [ ['arg1', 'arg2'] ]
$this->assertEquals([
0 =>[
0 => '1111',
1 => '2222',
],
],
$callsForMethod);
}
/** this clean is very important never miss it otherwise you will get trouble */
public function tearDown()
{
Moke::clean();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment