How can I check that the mockobject method was not called with only a specific parameter?

I have PHPUnit_Framework_MockObject_MockObject

a Logger

.

In a unit test, I don't want the method invocation to be warn

done with a special string parameter doNotCallMeWithThisString

.

I've come this far:

public function testThis()
{
    ...

    $logger = $this->getMockLogger();
    $logger->expects($this->exactly(0))->method('warn')->with(
        $this->equalTo('doNotCallMeWithThisString')
    );
    ...
}

      

However, this fails because it exactly(0)

marks any method invocation warn

as the error is even a string parameter somethingEntirelyUnrelated

.

How can I tell the layout that any call is warn

fine if it is not called with that specific line?

+3


source to share


2 answers


The method exactly()

is for asserting how many times the mocked method will be called. Unless you are using $this->at()

mock, you are not supplying arguments for a specific invocation. exactly(0)

says that the number of calls should be 0.

Change your layout to this:

 $logger->expects($this->any()) //Or however many times it should be called
        ->method('warn')
        ->with(
              $this->callback(function($argument) {
                  return $argument !== 'doNotCallMeWithThisString';
              })
         )
 );

      



This uses a callback to validate the argument passed to the mocked method and confirms that it is not equal to your string.

PHPUnit documentation has constraint types you can use to validate layout arguments. At the moment it has no string is not equal to type. But using a callback, you can make your own. Your callback just has to check the used argument and return true

if it's ok and false

if it's not.

+2


source


You can use assertion callback

. With this, the callback method you provided will be called every time this parameter is called:

$logger
    ->expects($this->any())
    ->method('warn')
    ->with($this->callback(function($string) {
        return $string !== 'doNotCallMeWithThisString';
    }));

      



Some important points:

  • Since you really don't like how often the method is called (or if it is called at all), unless it is called with a bad parameter, you need to use it $this->any()

    as a call count counter.
  • The callback constraint will be called for every call to the mocked method. It must returnTRUE

    to match.
+1


source







All Articles