0

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?

2
  • 1
    Is this helpful? stackoverflow.com/questions/3694117/… Commented Apr 10, 2022 at 0:20
  • 1
    Thanks you @JacobMulquin, my googling power is not workin anymore I guess :/ Commented Apr 10, 2022 at 0:39

2 Answers 2

1

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']);
...

Sign up to request clarification or add additional context in comments.

Comments

1

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’]);

2 Comments

Yes I did that finally, helpers functions like Laravel have ->assertJsonStructure() does not fit well :/
If tone of these assertions fail you'll get the message "Failed asserting that false is true". Not very helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.