Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

test if array contains value using PHPUnit

Tags:

php

phpunit

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

like image 422
Donoven Rally Avatar asked Jul 26 '15 14:07

Donoven Rally


People also ask

How do I run a PHPUnit test?

How to Run Tests in PHPUnit. You can run all the tests in a directory using the PHPUnit binary installed in your vendor folder. You can also run a single test by providing the path to the test file. You use the --verbose flag to get more information on the test status.

What is a PHPUnit test?

PHPUnit is a unit testing framework for the PHP programming language. It is an instance of the xUnit design for unit testing systems that began with SUnit and became popular with JUnit. Even a small software development project usually takes hours of hard work.

What is assertion in PHPUnit?

The assertion methods are declared static and can be invoked from any context using PHPUnit\Framework\Assert::assertTrue() , for instance, or using $this->assertTrue() or self::assertTrue() , for instance, in a class that extends PHPUnit\Framework\TestCase .

Why do we use PHPUnit?

PHPunit is mainly used for unit testing. When developer develops any web application, there might be chances of bugs coming into picture during the course of development. It is really hard to resolve one bug after another. PHPunit helps to reduce such types of bugs.


1 Answers

Try the assertContains method:

$this->assertContains( $randad, $adUnitArr ); 
like image 59
user2182349 Avatar answered Sep 30 '22 01:09

user2182349