'PHPUnit mock object with strict parameter comparison

With a mock object, I am able to quickly verify if a passed parameter of a method is equal to my original object thanks to the with method:

$hosting = new Hosting();

$this->entityManager
    ->expects($this->once())
    ->method('persist')
    ->with($hosting)
;
$this->persister->persist($hosting);

However, this test is not fully reliable. If I replace the $hosting parameter from the internal EntityManager::persist method by a new Hosting() instance, the test will pass when it should not.

To fix that, I have to put a custom callback:

$this->entityManager
    ->expects($this->once())
    ->method('persist')
    ->with(self::callback(static fn ($parameter) => $parameter === $hosting))
;

It works like a charm. However, I would like to have a simpler method call. Something like withSame.

I search on the official documentation without success.

Do we have a simpler way to achieve that?



Solution 1:[1]

I found a simpler way using the PHPUnit assert static function:

$this->entityManager
    ->expects($this->once())
    ->method('persist')
    ->with(self::identicalTo($hosting))
;

I found that by digging on the code where the callback function is defined. There are many more!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Soullivaneuh