1

I have a unit test which uses the following mocked class

$this->stubHandle = $this->getMockBuilder(Handle::class)->disableOriginalConstructor()->getMock();

When I run

$key = new Key($this->stubHandle);
$this->stubHandle->method('__call')->will($this->returnCallback('var_dump'));
$key->nonExistingMethod('element0', 'element1', []);

it outputs

string(17) "nonExistingMethod"

and

array(3) {
  [0] =>
  string(8) "element0"
  [1] =>
  string(8) "element1"
  [2] =>
  array(0) {
  }
}

which I think it means the first argument of method __call is a string and the second argument is an array. No more arguments passed.

When I mock the return value of method __call like

$this->stubHandle->method('__call')->willReturn(1);

The return value is always 1 as expected.

When I mock the return value of method __call like

$this->stubHandle->method('__call')->willReturnMap(
    [
        ['argument1', null, 'returnValue'],
    ]
);

I expect the return value to be 'returnValue' when the first argument of method __call is 'argument1' while the seconds argument doesn't care. If the first argument isn't 'argument1', I expect a return value of null.

Are these expectations correct?

No matter what I try, the return value is always null when I mock this value with method willReturnMap.

If my expectations are wrong, please lead me to a way to accomplish my goals to mock the return value, depending on the first argument (only) and also explain to me how to apply willReturnMap.

1 Answer 1

1

It seems my search for method willReturnMap mislead me a bit.
I was under the assumption using null in the map, it would act as a "don't care", but it literally means null.

$this->stubHandle->method('__call')->willReturnMap(
    [
        ['nonExistingMethod', null, 'returnValue'],
    ]
);

means the arguments of method __call must explicitly be 'nonExistingMethod' & null if you want the return value to be 'returnValue'. Any other argument-values will return null instead.
E.g. $key->nonExistingMethod(null);

For the map to return 'returnValue' in my example, it should have been:

$this->stubHandle->method('__call')->willReturnMap(
    [
        ['nonExistingMethod', ['element0', 'element1', []], 'returnValue'],
    ]
);
$key->nonExistingMethod('element0', 'element1', []);

In short... When using argument mapping, the values can't be a "don't Care".

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.