PHPUnit stubs - make expected calls independent of the order of invocation

倾然丶 夕夏残阳落幕 提交于 2020-01-06 14:17:11

问题


I have the following unit test code:

$map = [
   'key1' => 'A',
   'key2' => 'B'
]; 

$stub = $this->getMockBuilder('Phalcon\Session\Bag')
    ->setConstructorArgs([$sessionNamespace])
    ->getMock();

$stub->expects($this->at(0)) // Always called first by: new Phalcon\Session\Bag()
    ->method('setDI')
    ->will($this->returnCallback(function($di) {
        $this->di = $di;
}));

$stub->expects($this->at(1)) // First, we're checking if session key is set
    ->method('__isset')
    ->will($this->returnCallback(function($sessionKey) {
        // Yes, always set
        return true;
    }));

$stub->expects($this->at(2)) // Then, we're fetching it
    ->method('__get')
    ->will($this->returnValueMap($map));

I'm trying to return mapped values whenever __isset($key) or __get($key) are invoked on Phalcon\Session\Bag.

First invocation, everything works as expected:

$bag = new Phalcon\Session\Bag('someNamespace');
$var1 = (isset($bag->key1)) ? $bag->key1 : null; // $val1 is 'A'

However, all subsequent calls return NULL:

$var2 = (isset($bag->key2)) ? $bag->key2 : null; // $val1 is NULL
$var3 = (isset($bag->key1)) ? $bag->key1 : null; // $val1 is NULL

Obviously, the problem is with ->at(0|1), those are the position indices.

I have tried replacing ->at() with ->any(), but without luck - I was getting PHPUnit assertion error "Failed asserting that two strings are equal." - expected "__isset" does not match actual "setDI".

Question:

How can I tell expected methods of a stub to work irrespective of invocation order?

Thanks, Temuri

来源:https://stackoverflow.com/questions/19038038/phpunit-stubs-make-expected-calls-independent-of-the-order-of-invocation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!