Home > database >  Test an array and random value PHPunit
Test an array and random value PHPunit

Time:04-16

I have a little problem with my unit test and an array generated "randomly",

I have something looking like this :

return [
 'foo' => $this->faker->sentence(),
 'bar' => [
    'baz' => $this->faker->realText(),
    'booz' => [
       'baaz' => $this->faker->title()
    ]
 ]
];

$this->faker->xxx generate random strings or whatever, but I want to test the "shape" of the array, I want to ensure I have :

foo in first children array, bar too Bar have baz and booz at the same level and booz have a baaz in children.

But I could not find how to do that, I have tried something like this but it is not working :/

$this->assertEquals([
  'foo' => \Mockery::any(),
  'bar' => [
    'baz' => \Mockery::any(),
  ],
], $class->method());

Maybe this is not possible and I should find a way to simply test the keys in the array?

Maybe array_diff_key can help me here?

CodePudding user response:

Use multiple assertions:

$data = $class->method();
$this->assertTrue(isset($data[‘foo’]);
$this->assertTrue(isset($data[‘bar’]);
$this->assertTrue(is_array($data[‘bar’]);
$this->assertTrue(isset($data[‘bar’][‘baz’]);
$this->assertTrue(isset($data[‘bar’][‘booz’]);
$this->assertTrue(is_array($data[‘bar’][‘booz’]);
$this->assertTrue(isset($data[‘bar’][‘booz’][‘baaz’]);

CodePudding user response:

You should always try to use the most expressive assertion. assertEquals is for equality, assertTrue for booleans. But you only want to check the structure, so assertArrayHasKey', assertIsStringandassertIsArray` are your friends.

$this->assertArrayHasKey($data['foo']);
$this->assertIsString($data['foo']);

$this->assertIsArray($data['bar']);
$this->assertArrayHasKey($data['bar']['baz']);
$this->assertIsString($data['bar']['baz']);
...

  • Related