New constraint 'callback' for complex assertions. #206

Closed
wants to merge 1 commit into
from

Conversation

3 participants
Contributor

trapp commented Mar 17, 2011

Hi,

I've created a new constraint for matching against a callable. The reason for this are some limitations I ran into by mocking objects.

Imagine a method under test creates an object containing another object and you want to check the existance of both.

$object1 = new Object1();
$object1->setChild(new Object2('some property'));
$db->insert('TableName', $object1);

The test code for this would be something like:

// Create mock of database
$db = $this->getMock('SomeDatabaseClass');
// Set up expectations.
$db->expects($this->once())
     ->method('insert')
     ->with(
           $this->equalTo('TableName'),
           // Problem! How to check class of $object2 and value of $object1->getChild()->getProperty()?
        );

Is this a valid problem or is there a solution for this I just don't see.

This pull request solves this problem by accepting callbacks (including closures since php 5.3) as constraints:

// Create mock of database
$db = $this->getMock('SomeDatabaseClass');
// Set up expectations.
$db->expects($this->once())
   ->method('insert')
   ->with(
        $this->equalTo('TableName'),
        $this->callback(
            function ($object) {
                // Check for objects existance...
                // ...
                // Check value
                return $object->getChild()->getProperty() == 'some property';
            }
        )
    );

With php 5.3 one can use closures as in the example. Earlier versions of php can still use this feature using normal callbacks like array($object, 'method');

What do you think about this?

Contributor

lstrojny commented Mar 25, 2012

Nice!

@edorian edorian closed this in c2b43df Apr 1, 2012

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment