在phpunit中,是否有类似于onconsecutivecalls的方法用于“with”方法内部?

2022-08-30 21:30:34

使用PHPUnit,我正在嘲笑pdo,但我试图找到一种方法来准备多个数据库查询语句。

$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);

我想为“with”方法传递类似于onConsecutiveCalls的东西,这样我就可以准备多个语句,如上所示。你会怎么做呢?


答案 1

您可以通过编写单独的期望而不是来匹配相同方法的连续调用:$this->at()$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);

答案 2

PHPUnit 4.1 得到了一个新方法。来自测试双章withConsecutive()

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

的每个参数都用于对指定方法的一次调用。withConsecutive()


推荐