PHPUnit : Assert a parameter when pass it to mock object

烂漫一生 提交于 2019-12-22 01:42:31

问题


For the code below,

$mockObject->expects($this->at(0))
           ->method('search')
           ->with($searchConfig)
           ->will($this->returnValue([]));

This line will automatic make a assertensure that when it call method search it must contain $searchConfig parameters. In this case, we have to provide totally matched $searchConfig but sometime it is hard if it is an array or an object.

Are there any possible way to let PHPUnit call to some specific method to assert that it contains arguments pass in a method as we want?

For example, I may create closure function to assert as below instead of using ->with() method

function ($config){
    $this->assertFalse(isset($config['shouldnothere']));
    $this->assertTrue($config['object']->isValidValue());
}

回答1:


You can use ->with($this->callback()) and pass in a closure to perform more complex assertions on the argument.

From the PHPUnit Docs

The callback() constraint can be used for more complex argument verification. This constraint takes a PHP callback as its only argument. The PHP callback will receive the argument to be verified as its only argument and should return TRUE if the argument passes verification and FALSE otherwise.

Example 10.13: More complex argument verification

getMock('Observer', array('reportError'));

    $observer->expects($this->once())
             ->method('reportError')
             ->with($this->greaterThan(0),
                    $this->stringContains('Something'),
                    $this->callback(function($subject){
                      return is_callable(array($subject, 'getName')) &&
                             $subject->getName() == 'My subject';
                    }));

    $subject = new Subject('My subject');
    $subject->attach($observer);

    // The doSomethingBad() method should report an error to the observer
    // via the reportError() method
    $subject->doSomethingBad();
} } ?>

So your test would become:

$mockObject->expects($this->at(0))
->method('search')
->with($this->callback(
    function ($config){
        if(!isset($config['shouldnothere']) && $config['object']->isValidValue()) {
            return true;
        }
        return false;
    })
->will($this->returnValue([]));


来源:https://stackoverflow.com/questions/21181038/phpunit-assert-a-parameter-when-pass-it-to-mock-object

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