我有以下代码要测试。
// $generator, $locale, $site are parameters.
// It is just a part of real code.
$text = new Text();
$text->setType($generator->getType())
->setLocale($locale)
->setSite($site->getId());
/** @var $site 'namespace'Site */
$site->addText($text);
为了测试这一点,我正在使用嘲弄来模拟网站。
在测试中,我一般想做
$text = $site->getText();
$this->assertInstanceOF(''namespace'Text', $text);
$this->assertSame($generator->getType(), $text->getType());
$this->assertSame($locale, $text->getLocale());
$this->assertSame($site->getId(), $text->getSite());
在制作 mock 时,我希望 mock 返回由原始代码创建并设置在行$site->addText($site)
中的 Text 实例。我试过了
$text = new Text();
$site = Mockery::mock(Site::class)
->shouldReceive('addText')
->with($text)
->andReturnUsing(function() {
$args = func_get_args();
return $args[0];
})
->getMock();
这返回了在模拟代码中设置的文本对象。在嘲笑中,有什么方法可以让在原始代码中创建文本对象吗?
在这种情况下,您可以使用 Mockery::on()
方法。请参阅参数验证文档 。在这里,您可以传递一个闭包,该闭包接收传递给 addText 方法的参数。您还可以在此闭包中使用 PHPUnit 断言对$text
参数执行断言。喜欢这个:
$site = Mockery::mock(Site::class)
->shouldReceive('addText')
->with(Mockery::on(function($text) {
$this->assertInstanceOF(''namespace'Text', $text);
//More assertions
return true; //You must return true, otherwise the expectation will never pass regardless of the assertions above.
}));