我有一个如下的类:
class Foo extends BaseObject {
public static function grab() {
// do some DB search and return an instance of self
// with the data in the object
return new Foo($id);
}
public function insert() {
// insert the data in the database for this object
return false;
}
public function delete() {
// delete the data from the database for this object
return false;
}
}我如何模拟这个对象,同时仍然能够断言对insert和delete的调用按预期运行?
我所做的是:use AspectMock\Test;
$mock = Test::double('Foo', [
'grab' => Stub::make('Foo'),
'insert' => true,
'delete' => true,
]);
// ... later in the test ...
self::assertSame($foo->insert(), true);
$mock->verifyInvoked('insert', 1);这将绕过insert和update方法的模拟,返回false而不是预期的true。它也没有像预期的那样计算调用次数。
那么我怎样才能让mock自动返回呢?
(请原谅我在mock和stub之间造成的任何混淆)
发布于 2020-11-16 18:59:11
我建议您使用Phake来模拟静态方法as described here in the doc,例如:
public function testInsert()
{
/** @var \App\Foo $classUnderTest */
$classUnderTest = $this->getMockBuilder(Foo::class)
->disableOriginalConstructor()
->onlyMethods(['insert'])
->getMock();
$classUnderTest->expects($this->once())
->method('insert')
->willReturn(true);
/** @var \App\Foo $fooGrab */
$fooGrab = \Phake::mock(Foo::class);
\Phake::whenStatic($fooGrab)
->grab()
->thenReturn($classUnderTest);
$mock = $fooGrab::grab();
$this->assertTrue($mock->insert());
}https://stackoverflow.com/questions/64829677
复制相似问题