Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in phpunit, is there a method similar to onconsecutivecalls for use inside the "with" method?

Using PHPUnit, I'm mocking the pdo, but I'm trying to find a way to prepare more than one database query statement.

$pdo = $this->getPdoMock();
$stmt = $this->getPdoStatementMock($pdo);

$pdo->expects($this->any())
    ->method('prepare')
    ->with($this->equalTo($title_query))
    ->will($this->returnValue($stmt));

$title_stmt = $pdo->prepare($title_query);
$desc_stmt = $pdo->prepare($desc_query);

I want to pass something similar to onConsecutiveCalls for the "with" method, so I can prepare multiple statements, as seen above. How would you go about doing this?

like image 573
Francis Lewis Avatar asked Mar 16 '11 16:03

Francis Lewis


Video Answer


2 Answers

You can match consecutive invocations of the same method by writing separate expectations with $this->at() instead of $this->any():

$pdo->expects($this->at(0))
    ->method('prepare')
    ->with($this->equalTo($title_query))
    ->will($this->returnValue($stmt));

$pdo->expects($this->at(1))
    ->method('prepare')
    ->with($this->equalTo($desc_query))
    ->will($this->returnValue($stmt));

$title_stmt = $pdo->prepare($title_query);
$desc_stmt = $pdo->prepare($desc_query);
like image 199
Vika Avatar answered Nov 15 '22 13:11

Vika


PHPUnit 4.1 got a new method withConsecutive(). From the Test Double Chapter:

class FooTest extends PHPUnit_Framework_TestCase
{
    public function testFunctionCalledTwoTimesWithSpecificArguments()
    {
        $mock = $this->getMock('stdClass', array('set'));
        $mock->expects($this->exactly(2))
             ->method('set')
             ->withConsecutive(
                 array($this->equalTo('foo'), $this->greaterThan(0)),
                 array($this->equalTo('bar'), $this->greaterThan(0))
             );

        $mock->set('foo', 21);
        $mock->set('bar', 48);
    }
}

Each argument of withConsecutive() is for one call to the specified method.

like image 44
ThW Avatar answered Nov 15 '22 14:11

ThW