web-dev-qa-db-ja.com

PHPUnit:配列に指定された値のキーがあることを確認する

次のクラスがあるとします。

_<?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);
    }
}
_

そして、このテストケース:

_<?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();
    }
_

_$params_(配列)と$Other->post()に渡されるキーが、「値1」の値を持つ「key1」という名前のキーを含むことをどのように確認しますか?

すべての配列を確認したくありません-これは単なるサンプルコードです。実際のコードでは、渡された配列にはより多くの値が含まれています。その中の1つのキーと値のペアだけを確認します。

キーが存在することを確認するために使用できる$this->arrayHasKey('keyname')があります。

配列にこの値があることを確認するために使用できる$this->contains('Value 1')もあります。

これら2つを_$this->logicalAnd_と組み合わせることもできます。しかし、これはもちろん望ましい結果をもたらしません。

これまでのところ、私はreturnCallbackを使用して$ params全体をキャプチャし、それに対してアサートを行っていますが、おそらく私がやりたいことを行う別の方法はありますか?

37
Anti Veeranna

属性1に基づいて、独自の制約クラスを作成することになりました

<?php
class Test_Constraint_ArrayHas extends PHPUnit_Framework_Constraint
{
    protected $arrayKey;

    protected $constraint;

    protected $value;

    /**
     * @param PHPUnit_Framework_Constraint $constraint
     * @param string                       $arrayKey
     */
    public function __construct(PHPUnit_Framework_Constraint $constraint, $arrayKey)
    {
        $this->constraint  = $constraint;
        $this->arrayKey    = $arrayKey;
    }


    /**
     * Evaluates the constraint for parameter $other. Returns TRUE if the
     * constraint is met, FALSE otherwise.
     *
     * @param mixed $other Value or object to evaluate.
     * @return bool
     */
    public function evaluate($other)
    {
        if (!array_key_exists($this->arrayKey, $other)) {
            return false;
        }

        $this->value = $other[$this->arrayKey];

        return $this->constraint->evaluate($other[$this->arrayKey]);
    }

    /**
     * @param   mixed   $other The value passed to evaluate() which failed the
     *                         constraint check.
     * @param   string  $description A string with extra description of what was
     *                               going on while the evaluation failed.
     * @param   boolean $not Flag to indicate negation.
     * @throws  PHPUnit_Framework_ExpectationFailedException
     */
    public function fail($other, $description, $not = FALSE)
    {
        parent::fail($other[$this->arrayKey], $description, $not);
    }


    /**
     * Returns a string representation of the constraint.
     *
     * @return string
     */
    public function toString ()
    {
        return 'the value of key "' . $this->arrayKey . '"(' . $this->value . ') ' .  $this->constraint->toString();
    }


    /**
     * Counts the number of constraint elements.
     *
     * @return integer
     */
    public function count ()
    {
        return count($this->constraint) + 1;
    }


    protected function customFailureDescription ($other, $description, $not)
    {
        return sprintf('Failed asserting that %s.', $this->toString());
    }

次のように使用できます。

 ... ->with(new Test_Constraint_ArrayHas($this->equalTo($value), $key));
8
Anti Veeranna

$this->arrayHasKey('keyname');メソッドは存在しますが、その名前はassertArrayHasKeyです。

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

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

再利用可能な制約クラスを作成する代わりに、PHPUnitの既存のコールバック制約を使用して配列キーの値をアサートすることができました。私の使用例では、モック化されたメソッドの2番目の引数で配列値を確認する必要がありました( MongoCollection :: ensureIndex() 、興味がある場合)。これが私が思いついたものです:

$mockedObject->expects($this->once())
    ->method('mockedMethod')
    ->with($this->anything(), $this->callback(function($o) {
        return isset($o['timeout']) && $o['timeout'] === 10000;
    }));

callback constraint は、コンストラクターでcallableを期待し、評価中にそれを呼び出すだけです。アサーションは、callableがtrueまたはfalseを返すかどうかに基づいて成功または失敗します。

大規模なプロジェクトの場合、(上記のソリューションのように)再利用可能な制約を作成するか、または PR#312 をPHPUnitにマージするよう請願することをお勧めしますが、これは1つのトリックです-時間の必要性。コールバック制約がより複雑なアサーションにもどのように役立つかを簡単に確認できます。

15
jmikola

パラメータで複雑なテストを行い、有用なメッセージと比較もしたい場合は、コールバック内にアサーションを配置するオプションが常にあります。

例えば.

$clientMock->expects($this->once())->method('post')->with($this->callback(function($input) {
    $this->assertNotEmpty($input['txn_id']);
    unset($input['txn_id']);
    $this->assertEquals($input, array(
        //...
    ));
    return true;
}));

コールバックがtrueを返すことに注意してください。そうしないと、常に失敗します。

3
Dane Lowe