LoginSignup
6
3

More than 3 years have passed since last update.

LaravelにAspectMock

Last updated at Posted at 2018-02-06

追記

laravel/framework (v5.5.33 => v5.5.39)

にして

goaop/framework (2.1.2 => 2.2.0)

になったらエラーが出るようになりました。

PHP Fatal error:  Uncaught RuntimeException: You need to provide valid cache directory for Go! AOP framework

GoAOP deprecated StreamMetaData->source

goaop/framework

2.2.0からエラー

cacheDirが必須になっていた。
これを追加してもエラーなので

"goaop/framework": "2.1.2",

で戻してインストールを行えば良い。

こっちでデフォルト値(/tmp)を設定するかもしれない。

使い方

AspectMock

インストール

composer require codeception/aspect-mock:* --dev

設定

tests/autoload.php
<?php

require_once __DIR__ . '/../vendor/autoload.php';

$kernel = \AspectMock\Kernel::getInstance();
$kernel->init([
    'debug' => true,
    'includePaths' => [
        __DIR__.'/../app',
        __DIR__.'/../vendor/laravel',
    ],
    // 'cacheDir' => '/tmp',// goaop/framework 2.2.0から必須
]);
phpunit.xml
- bootstrap="vendor/autoload.php"
+ bootstrap="tests/autoload.php"
tests\TestCase.php
use AspectMock\Test as AspectMockTest;

~~~~~~~~~~~~~~~~~~~~~~~~~~~~

protected function tearDown()
{
    AspectMockTest::clean(); // remove all registered test doubles
}

使い方

use AspectMock\Test as AspectMockTest;

モック

$test = AspectMockTest::double('Namespace\User', ['getName' => 'user_name']);

// 実行後に以下で呼び出し確認もできる。(@expectedExceptionを使う場合は確認できないのでtrycatchを使って確認する)
//    $test->verifyInvoked('getName');
//    $test->verifyInvokedOnce('getName');
//    $test->verifyNeverInvoked('getName');
//    $test->verifyInvokedMultipleTimes('getName',1);
//    $test->verifyInvokedOnce('getName', ['argument']);
//    $test->verifyInvokedMultipleTimes('getName', 2, ['argument']);

モック結果を引数によって分ける

$test = AspectMockTest::double('Namespace\User', ['getName' => function ($argument) {
    // $argumentを判定して結果をreturnする
    // return __AM_CONTINUE__ とすれば元のメソッドの動作を行う
}]);

順番に返り値を設定する

$mock_index = 0;
$test = AspectMockTest::double('Namespace\User', ['getName' => function ($argument) use (&$mock_index) {
    $return_list = ['first', 'second', 'third'];
    return $return_list[$mock_index++];
}]);

PHPの標準関数のモック

namespace demo;
AspectMockTest::func('Namespace', 'time', 'now');
$this->assertEquals('now', time());

第三引数がresultOrClosureとなっていたのでクロージャも設定可能

AspectMockTest::func('Namespace', 'date', function ($argument) {
    if ($argument === 'Y-m-d H:i:s')
    {
        return '2019-01-01 00:00:00';
    }
    if ($argument === 'Y')
    {
        return '2019';
    }
});

第一引数はnamespaceであることに注意。クラス名までは設定しないこと。

参考

6
3
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
3