Assert equal time with some tolerance in phpunit

73 Views Asked by At

I am just starting with phpunit and this is where I have little problem now. The class I'm writing a test for, has a Logger method which when called, adds the timestamp to a property, Like this:

        $this->logger->info('Log created', [
        'user_id' => $order->getCustomerId(),
        'time' => microtime(true),
    ]);

Now in my test class after creating a new mock object of that class, this is how I check to see if some given mock data equals to my logger:

        $this->logger
        ->expects($this->once())
        ->method('info')
        ->with(
            $this->equalTo('Campaign code created'),
            $this->equalTo(['user_id' => 2000, 'time' => **??**])
        );

How can I change the question marks to assert this array equal to the time when it gets created? Or is there a way that I can't check this property at all? because right now without the time property it throws an error.

1

There are 1 best solutions below

0
On

There is equalToWithDelta which might actually work (it's essentially identical to assertEqualsWithDelta, the delta is just ignored for strings but applied to all numbers). However, since the delta is applied to all values of the array, this might pose a problem if you have something like ids in the array as well. So, depending on your test, that might be okay ...

However, there is also callback which takes a function as an argument, which will allow you to make more sophisticated tests on the spot. Not done this but rather found in the source code, so I hope this solution is correct:

$this->callback(function ($value) {
    return $value['user_id'] == 2000 
        && $value['time'] >= $minTime
        && $value['time'] <= $maxTime;
})

The class that is used by callback is the Callback constraint

You could also write a custom comparator, which I guess would go far and beyond the solution you're looking for.