Test that method is called with some parameters, among others

拈花ヽ惹草 提交于 2019-12-24 03:00:31

问题


I'm testing a method with phpunit and I have the following scenario:

  • method 'setParameter' is called an unkown amount of times
  • method 'setParameter' is called with different kinds of arguments
  • among the various arguments method 'setParameter' MUST be called with a set of arguments.

I've tried doing it this way:

$mandatoryParameters = array('param1', 'param2', 'param3');
foreach ($mandatoryParameters as $parameter) {
    $class->expects($this->once())
        ->method('setParameter')
        ->with($parameter);
}

Unfortunately the test failed because before method is called with these parameters it is called with other parameters too. The error i get is:

Parameter 0 for invocation Namespace\Class::setParameter('random_param', 'random_value')
does not match expected value.
Failed asserting that two strings are equal.

回答1:


Try using the $this->at() method. You are overwriting your mock each time with your loop.

$mandatoryParameters = array('param1', 'param2', 'param3');
$a = 0;
foreach ($mandatoryParameters as $parameter) {
    $class->expects($this->at($a++);
        ->method('setParameter')
        ->with($parameter);
}

This will set your mock to expect setParameter to be called a certain number of times and each call will be with a different parameter. You will need to know which call is the specific on for your parameters and adjust the number accordingly. If the calls are not sequential, you can set a key for which index each param.

$mandatoryParameters = array(2 =>'param1', 5 => 'param2', 6 => 'param3');

foreach ($mandatoryParameters as $index => $parameter) {
    $class->expects($this->at($index);
        ->method('setParameter')
        ->with($parameter);
}

The index is zero based so remember to start your counting from 0 rather than 1.

http://phpunit.de/manual/current/en/phpunit-book.html#test-doubles.mock-objects.tables.matchers



来源:https://stackoverflow.com/questions/22607190/test-that-method-is-called-with-some-parameters-among-others

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