有没有办法为不同的输入参数定义不同的mock-expects?例如,我有一个名为DB的数据库层类。这个类有一个名为"Query ( string SQL )“的方法,该方法在输入时接受$query查询字符串。我可以为这个类(DB)创建模拟,并为依赖于输入查询字符串的不同查询方法调用设置不同的返回值吗?
发布于 2014-05-02 12:15:13
看起来Mockery (https://github.com/padraic/mockery)支持这一点。在我的例子中,我想检查是否在数据库上创建了两个索引:
嘲笑,作品:
use Mockery as m;
//...
$coll = m::mock(MongoCollection::class);
$db = m::mock(MongoDB::class);
$db->shouldReceive('selectCollection')->withAnyArgs()->times(1)->andReturn($coll);
$coll->shouldReceive('createIndex')->times(1)->with(['foo' => true]);
$coll->shouldReceive('createIndex')->times(1)->with(['bar' => true], ['unique' => true]);
new MyCollection($db);
PHPUnit,这将失败:
$coll = $this->getMockBuilder(MongoCollection::class)->disableOriginalConstructor()->getMock();
$db = $this->getMockBuilder(MongoDB::class)->disableOriginalConstructor()->getMock();
$db->expects($this->once())->method('selectCollection')->with($this->anything())->willReturn($coll);
$coll->expects($this->atLeastOnce())->method('createIndex')->with(['foo' => true]);
$coll->expects($this->atLeastOnce())->method('createIndex')->with(['bar' => true], ['unique' => true]);
new MyCollection($db);
Mockery也有更好的语法IMHO。它看起来比PHPUnits内置的模拟功能要慢一点,但YMMV。
https://stackoverflow.com/questions/5988616
复制相似问题