AspectMock icon indicating copy to clipboard operation
AspectMock copied to clipboard

Best way to return multiple values from mocked methods

Open sahanh opened this issue 10 years ago • 5 comments

One of the classes I'm mocking is called few times along the process and from what I read in the docs, I can only return a single value when defining the mock. Is there a way to change the returning values on each call?

sahanh avatar Dec 31 '14 16:12 sahanh

How about this?

test::double('Fuel\Core\Config', ['get' => function ($arg) {
    if ($arg === 'foo.bar') {
        return 'foo.bar';
    } else {
        return 'baz';
    }
}]);

kenjis avatar Dec 31 '14 23:12 kenjis

wonderful thank you @kenjis

sahanh avatar Jan 01 '15 00:01 sahanh

Reopening to see if there are other methods when no arguments are passed to the method.

sahanh avatar Jan 01 '15 01:01 sahanh

This should be the same:

test::double(Some::class, ['get' => function () {
    static $index = 0;
    $mockValues = ['foo', 'bar', 'baz'];

    return $mockValues[$index++];
}]);

lisachenko avatar Jan 05 '15 16:01 lisachenko

$arg = 'foo';
test::double(Some::class, ['hoge' => function () use ($arg) {
     if ($arg == 'foo' ) {
        return 'foo' ; 
     }
     return 'bar';
}]);

$i =1;
test::double(Some::class, ['hoge' => function () use (&$i) {
     if ($i == 1 ) {
        $i++;
        return '1 time' ; 

     } else if ($i == 2) {
        $i++;
        return '2 times';
   }
    return __AM_CONTINUE__;
}]);

seikei1874 avatar Jan 06 '15 05:01 seikei1874