PHPUnit: Verifying that array has a key with given value

Anti Veeranna picture Anti Veeranna · Sep 28, 2009 · Viewed 35.2k times · Source

Given the following class:

<?php
class Example {
    private $Other;

    public function __construct ($Other)
    {
        $this->Other = $Other;
    }

    public function query ()
    {   
        $params = array(
            'key1' => 'Value 1'
            , 'key2' => 'Value 2'
        );

        $this->Other->post($params);
    }
}

And this testcase:

<?php
require_once 'Example.php';
require_once 'PHPUnit/Framework.php';

class ExampleTest extends PHPUnit_Framework_TestCase {

    public function test_query_key1_value ()
    {   
        $Mock = $this->getMock('Other', array('post'));

        $Mock->expects($this->once())
              ->method('post')
              ->with(YOUR_IDEA_HERE);

        $Example = new Example($Mock);
        $Example->query();
    }

How do I verify that $params (which is an array) and is passed to $Other->post() contains a key named 'key1' that has a value of 'Value 1'?

I do not want to verify all of the array - this is just a sample code, in actual code the passed array has a lot more values, I want to verify just a single key/value pair in there.

There is $this->arrayHasKey('keyname') that I can use to verify that the key exists.

There is also $this->contains('Value 1'), which can be used to verify that the array has this value.

I could even combine those two with $this->logicalAnd. But this of course does not give the desired result.

So far I have been using returnCallback, capturing the whole $params and then doing asserts on that, but is there perhaps another way to do what I want?

Answer

air-dex picture air-dex · Jun 5, 2014

The $this->arrayHasKey('keyname'); method exists but its name is assertArrayHasKey :

// In your PHPUnit test method
$hi = array(
    'fr' => 'Bonjour',
    'en' => 'Hello'
);

$this->assertArrayHasKey('en', $hi);    // Succeeds
$this->assertArrayHasKey('de', $hi);    // Fails