PHPUnit: проверка того, что массив имеет ключ с заданным значением

Это означает, что узел не может прослушивать определенный порт. Измените его на 1234 или 2000 или 3000 и перезапустите сервер.

34
задан Anew 12 February 2013 в 16:44
поделиться

2 ответа

Я закончил создание моего собственного класса ограничений на основе атрибута one

<?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
ответ дан 27 November 2019 в 07:01
поделиться

Извините, я не говорю по-английски.

Я думаю, что вы можете проверить, существует ли ключ в массиве с помощью функции array_key_exists, и вы можете проверить, существует ли значение с помощью array_search

Например:

function checkKeyAndValueExists($key,$value,$arr){
    return array_key_exists($key, $arr) && array_search($value,$arr)!==false;
}

Используйте ! == , потому что array_search возвращает ключ этого значения, если он существует, и он может быть 0.

-4
ответ дан 27 November 2019 в 07:01
поделиться
Другие вопросы по тегам:

Похожие вопросы: