68

I created this array of objects:

$ad_1 = new AdUnit(array('id' => '1', 'name' => 'Ad_1', 'description' => 'great ad', 'code' => 'alpha', 'widget_id' => '123'));
$ad_2 = new AdUnit(array('id' => '2', 'name' => 'Ad_2', 'description' => 'good ad', 'code' => 'delta', 'widget_id' => '456'));
$ad_3 = new AdUnit(array('id' => '3', 'name' => 'Ad_3', 'description' => 'bad ad', 'code' => 'sigma', 'widget_id' => '789'));
$adUnitArr = array($ad_1, $ad_2, $ad_3);

and i want to check that a random ad i got from a function exists in the array. the code to get the ad looks like this:

        $fixture = new AdGroup();
$fixture->setAds($adUnitArr);
$randad = $fixture->getRandomAd();

now i want to check if the array contains the random ad i received, what i was able to do like this:

$this->assertEquals(in_array($randad, $adUnitArr), 1); //check if ad in array

but my question is, is there an assert or some other way to check this thing better than the way i did it?? i tried using assertArrayHasKey but i got the following error:

PHPUnit_Framework_Exception: Argument #1 (No Value) of PHPUnit_Framework_Assert::assertArrayHasKey() must be a integer or string

any idea please? thx

Donoven Rally
  • 1,670
  • 2
  • 17
  • 34

1 Answers1

123

Try the assertContains method:

$this->assertContains( $randad, $adUnitArr );
user2182349
  • 9,569
  • 3
  • 29
  • 41
  • 26
    Beware of `bool`. `$this->assertContains('foo', ['abc' => true]);` will be true. – GeekMagus Apr 12 '17 at 03:01
  • This is definitely a bug? Is it fixed? – Chibueze Opata Mar 23 '20 at 13:20
  • 2
    @ChibuezeOpata it is not a bug but an edge case. It happens because of loose comparison of 'foo' == true. Converting non empty string to boolean in php will result in true. You have to be aware of it all the time when working with php. To force strict comparison you can use `$this->assertContains('foo', ['abc' => true], '', false, true, true);` which is ugly – valerij vasilcenko Oct 08 '20 at 11:31
  • 1
    That's one perspective. Bugs are always edge cases. They are called bugs because they're not expected. – Chibueze Opata Oct 08 '20 at 19:14
  • 1
    @ChibuezeOpata At least in PHPUnit 9.6 the test described by GeekMagus does not pass. Also if the contract allows you to configure loose/strict comparison it's most def not a bug regardless if the signature of the contract is ugly or not. – vitoriodachef Jul 16 '21 at 13:17