【问题标题】:Create mock and stub method that returns self mock创建返回自我模拟的模拟和存根方法
【发布时间】:2021-02-25 23:29:21
【问题描述】:

我有一堂课如下:

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;
    }

}

如何模拟此对象,同时仍保留断言对 insertdelete 的调用按预期运行的能力?

我所做的是: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);

这绕过了 insertupdate 方法的模拟,并返回 false 而不是预期的 true。它也不会按预期计算调用。

那么我怎样才能让 mock 自己返回呢?

(请原谅我可能在mockstub 之间造成的任何混淆)

【问题讨论】:

    标签: php unit-testing mocking phpunit codeception


    【解决方案1】:

    我建议你使用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());
    }
    

    【讨论】:

    • 我希望能够在不导入另一个完整包的情况下做到这一点,只是为了让这个测试通过。
    • @Benjam 我了解,但 PHPUnit 不支持静态模拟,而且似乎 Codeception。您在该项目中实际使用的是哪个测试框架?
    • AspectMock 也作为该软件包的一部分提供。我们正在使用 Codeception,它使用 PHPUnit 作为它的基础。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-15
    • 2011-09-30
    • 1970-01-01
    • 2022-11-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多