0

I want a mock object that can tell me if:

  1. when one of its methods are called
  2. that one of the arguments passed to that method
  3. is an array
  4. and has a particular key/value pair.

I want to use PHPUnit's constraints to achieve, this, so my test code would look like this:

$mock = $this->getMock('\Jodes\MyClass');
$mock->expects($this->once())
        ->method('myMethod')
        ->with(
                $this->logicalAnd(
                    $this->isType('array'),
                    $this->arrayHasPair('my_key', 'my_value'),
                )
            );
// ... code here that should call the mock method

In this previous SO question, the guy ended up writing his own constraint.

I found this library which seems to implement quite a few nifty things. So I installed it by adding this line in my composer.json's require section:

"etsy/phpunit-extensions": "@stable"

But when I try using it, I get an error. I use it like so:

class MyClassTest extends PHPUnit_Framework_TestCase {
    public function arrayHasPair($key, $value){
        return new PHPUnit_Extensions_Constraint_ArrayHasKeyValuePair($key, $value);
    }
    public function testmyMethod(){
        // code as per my example above
    }
}

But that produces this error:

PHP Fatal error: Call to undefined method PHPUnit_Util_Type::export() in C:\MyProject\vendor\etsy\phpunit-extensions\PHPUnit\Extensions\Constraint\ArrayHasKeyValuePair.php on line 50

This previous question/answer explains what the problem is, but I'm not sure what I should do about it. Does this mean that the developers of that library have abandoned it? Is there an alternative to use? Or what options do I have for fixing it? I'm amazed such basic constraints still don't exist in PHPUnit. Obviously I could write my own constraints but surely that's unnecessary?

3
  • 1
    I've been using Mockery and Hamcrest for this kind of constraint. Works well for me.
    – Simba
    Aug 19, 2015 at 13:00
  • Thanks, looks brilliant! Trying it out now.
    – Jodes
    Aug 19, 2015 at 13:15
  • @Simba, do you know how I can use mockery/hamcrest to test if an argument is an array that contains a key/value pair? Would I need to write a closure that looks for the pair?
    – Jodes
    Aug 19, 2015 at 13:51

1 Answer 1

0

The PHPUnit_Util_Type::export() method was removed a while ago. The extension you want to use has to be updated to be compatible with current versions of PHPUnit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.