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)
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)
归档时间: |
|
查看次数: |
7799 次 |
最近记录: |