PHPUnit Float Mistake

facepalm

Yesterday I ran into a frustrating situation while I was writing a unit test for some new code that I was working on. I had a test that was expecting a mock to have one of its methods called a specific number of times.

$myMock->expects($this->exactly(3))->method('myMethod');
$myObject->doSomething();

Only I was trying to avoid having too many static values defined all over my test case so I was calculating the number of times the method would be called.

$callCount = ceil(self::TOTAL / self::LIMIT);
$myMock->expects($this->exactly($callCount))->method('myMethod');
$myObject->doSomething();

The issue I was having was that my test kept failing but the reason it was failing didn’t seem to make any sense.

Method was expected to be called 3 times, actually called 3 times.

My google searches for what this might be turned up nothing. So I then tried simplifying the test. That is when I noticed that if I changed the calculated count to a integer everything worked fine. What I didn’t take into account is that in PHP the ceil() method returns a float and PHPUnit apparently does an exact comparison (===) of the number of times a method is expected to be called an the number of times it is actually called. But when the failure is output the float of value 3 prints exactly the same as the integer value of 3, thus my confusion.

In the end what I did was to cast the result of the ceil() to an integer since I know that the number will not be large enough to be an issue.

$callCount = (int) ceil(self::TOTAL / self::LIMIT);
$myMock->expects($this->exactly($callCount))->method('myMethod');
$myObject->doSomething();