在phpunit中,是否有类似onconsecutivecalls的方法在"with"方法中使用?

Fra*_*wis 14 php junit phpunit pdo unit-testing

使用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);
Run Code Online (Sandbox Code Playgroud)

我想传递一些类似onConsecutiveCalls的"with"方法,所以我可以准备多个语句,如上所示.你会怎么做呢?

小智 23

您可以通过编写单独的期望来匹配相同方法的连续调用,$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);
Run Code Online (Sandbox Code Playgroud)

  • 请注意,计数器是针对收到的*all*方法调用的每个模拟.因此,如果要对`$ pdo`进行两次干预调用,则使用0和3. (6认同)

ThW*_*ThW 15

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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


Nat*_*ate 10

使用更新版本的PHPUnit,可以简化接受的答案.

另外,虽然它与原始问题不直接相关,但您可以通过该方法轻松地为每个方法调用提供不同的返回值willReturnOnConsecutiveCalls.

$pdo->expects($this->exactly(2))
    ->method('prepare')
    ->withConsecutive(
        $this->equalTo($title_query),
        $this->equalTo($desc_query)
    )
    ->willReturnOnConsecutiveCalls(
        $stmt, // returned on the 1st call to prepare()
        $stmt  // returned on the 2nd call to prepare()
    );
Run Code Online (Sandbox Code Playgroud)