71

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

2
  • 2
    $this->assertEquals((int) in_array($randad, $adUnitArr), 1); //check if ad in array Commented Jul 26, 2015 at 14:43
  • 3
    $this->assertTrue(in_array($randad, $adUnitArr)); Commented Sep 7, 2017 at 12:23

1 Answer 1

128

Try the assertContains method:

$this->assertContains( $randad, $adUnitArr );
Sign up to request clarification or add additional context in comments.

5 Comments

Beware of bool. $this->assertContains('foo', ['abc' => true]); will be true.
This is definitely a bug? Is it fixed?
@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
That's one perspective. Bugs are always edge cases. They are called bugs because they're not expected.
@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.

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.