Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assert an object value is within a range in PHPUnit

I'm fairly new to using PHPUnit, so I hope this isn't a time-wasting question:

I have a set of tests which assert equals on an object.

The issue is when the dates are set, the date/time might be off by 1 second. I know it is possible to assert a value is between two values, like so:

$this->assertThat(
    $testFloat,
    $this->logicalAnd(
        $this->greaterThan(1.65),
        $this->lessThan(1.66)
    )
);

However, my value resides inside an object, so my assertEquals fails.

Can anybody help, or give some clues how to work around this?

like image 387
Steve Borland Avatar asked Sep 25 '26 14:09

Steve Borland


1 Answers

Your best option is to refactor either your tests or your code so that the time won't be off by a second and the objects will be equal. Without seeing the code, I am not sure exactly what you want to do. But I am guessing that you are creating a date/time in your code that you are testing. Make the time a parameter that you have to provide and then you don't have to worry about being off by a second or anything.

Something that is hard to test is a code smell. Change the code to make it easier to test. If that isn't an option, then you will have to not compare objects. Instead, I would check the type of the object and examine all of the public properties to make sure that things were correct.

assertEquals also can take a delta for comparing values.

https://phpunit.readthedocs.io/en/7.1/assertions.html#assertequals

assertEquals(float $expected, float $actual[, string $message = '', float $delta = 0])

Though I don't think that this will work for objects. It was intended for floating point comparisons.

like image 162
Schleis Avatar answered Sep 28 '26 04:09

Schleis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!