LoginSignup
1
1

More than 5 years have passed since last update.

CodeIgniterのPHPUnitでモックの返り値を動的に設定する

Last updated at Posted at 2018-06-10

ci-phpunit-testのモンキーパッチを使用して返り値を動的に設定する際の書き方

返り値を設定

$return_list = [1, 2, 3];
$index = 0;

MonkeyPatch::patchMethod(
    'Class',
    [
        'method' => function ($argument) use ($return_list, &$index) {
            return $return_list[$index++];// 呼ばれた順で返り値を設定($argumentで判定して出しわけもできます)
        },
    ]
);

または

$return_list = [1, 2, 3];

MonkeyPatch::patchMethod(
    'Class',
    [
        'method' => function ($argument) use ($return_list) {
            static $index = 0;
            return $return_list[$index++];// 呼ばれた順で返り値を設定($argumentで判定して出しわけもできます)
        },
    ]
);

呼び出し確認

MonkeyPatch::verifyInvokedMultipleTimes('Class::method', 3);
1
1
0

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
1
1