首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >phpunit模拟方法具有不同参数的多个调用

phpunit模拟方法具有不同参数的多个调用
EN

Stack Overflow用户
提问于 2011-05-13 15:25:28
回答 1查看 108.7K关注 0票数 137

有没有办法为不同的输入参数定义不同的mock-expects?例如,我有一个名为DB的数据库层类。这个类有一个名为"Query ( string SQL )“的方法,该方法在输入时接受$query查询字符串。我可以为这个类(DB)创建模拟,并为依赖于输入查询字符串的不同查询方法调用设置不同的返回值吗?

EN

回答 1

Stack Overflow用户

发布于 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。

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5988616

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档