Home > Software engineering >  Error asserting a float in JSON with PHPUnit
Error asserting a float in JSON with PHPUnit

Time:01-30

Context : I created an app with Symfony and API Platform and I'm writing tests for the API

I have a property name "cost" which is a float in my entity:

#[ApiResource()]
class MyEntity {
...
    #[ORM\Column(nullable: true)]
    private ?float $cost = null;
..
}

This property is stored as "double precision" in my Postgres DB (which is managed by Doctrine).

This entity as an API endpoint generated by API Platform. I wrote test to check if the values are correct:

public function testGetSingleMyEntity(): void
{
...
$client->request('GET', '/api/my_entity/'.$myentity->getId());
$this->assertJsonContains([
    "cost" => $myentity->getCost()
]);
...
}

But when I run the test, I have this error:

3) App\Tests\Api\MyEntityTest::testGetSingleMyEntity
Failed asserting that an array has the subset Array &0 (
    'cost' => 25.0
--- Expected
    Actual
@@ @@
-  'cost' => 25.0,
   'cost' => 25,

I tried casting the value of cost with (float) or floatval but I doesn't change anything as it's already a float.

I don't understand if it's a type formatting error from API Platform or because I made an error?

I would really appreciate if someone could tell me what's the issue here.

Thanks

CodePudding user response:

To fix the issue I had to change the type of the property cost to "decimal". It's now stored as a numeric(10,2) into the DB and handled as a string in PHP :

#[ApiResource()]
class MyEntity {
...
    #[ORM\Column(type: "decimal", precision: 10, scale: 2, nullable: true)]
    private ?string $cost = null;

    public function getCost(): ?string
    {
        return $this->cost;
    }

    public function setCost(?string $cost): self
    {
        $this->cost = $cost;

        return $this;
    }
...
}
  • Related